如何从python执行命令提示符命令

Adr*_*ian 29 python windows

我试过这样的事,但没有效果:

command = "cmd.exe"
proc = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
proc.stdin.write("dir c:\\")
Run Code Online (Sandbox Code Playgroud)

rmf*_*low 47

怎么样简单:

import os
os.system('dir c:\\')
Run Code Online (Sandbox Code Playgroud)


Dar*_*mas 19

你可能想尝试这样的事情:

command = "cmd.exe /C dir C:\\"

我不认为你可以管道cmd.exe......如果你是来自unix背景,那么,cmd.exe有一些丑陋的疣!

编辑:根据斯文马纳赫,你可以管道cmd.exe.我试着在python shell中关注:

>>> import subprocess
>>> proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
>>> stdout, stderr = proc.communicate('dir c:\\')
>>> stdout
'Microsoft Windows [Version 6.1.7600]\r\nCopyright (c) 2009 Microsoft Corporatio
n.  All rights reserved.\r\n\r\nC:\\Python25>More? '
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,您仍然需要做一些工作(只返回第一行),但您可能能够使其工作......

  • @Jan-Bert 尝试将 `b` 放在它前面,像这样:`b'byte string here'`。这可能是由于这个答案的年龄,并且它使用的是 Python 2,而不是 3。查看 https://docs.python.org/3/howto/pyporting.html#text-versus-binary-data。 (3认同)

小智 11

尝试:

import os

os.popen("Your command here")
Run Code Online (Sandbox Code Playgroud)

  • 请提供一些细节。 (4认同)

nco*_*lan 6

proc.stdin.flush()在写入管道后尝试添加一个调用,看看事情是否开始按预期运行.明确刷新管道意味着您无需担心如何设置缓冲区.

此外,不要忘记"\n"在命令的末尾包含一个或者您的子shell将在提示符处等待命令条目的完成.

我写了一篇关于使用Popen更详细地操作外部shell实例的文章:使用Python在同一进程中运行三个命令

与该问题中的情况一样,如果您需要在Windows计算机上跨多个进程外调用维护shell状态,则此技巧可能很有用.


gki*_*sey 6

从 Daren Thomas 的回答(和编辑)中获得一些灵感,试试这个:

proc = subprocess.Popen('dir C:\\', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = proc.communicate()
Run Code Online (Sandbox Code Playgroud)

out 现在将包含文本输出。

这里的关键是subprocess 模块已经为您提供了 shell 集成shell=True,因此您不需要直接调用 cmd.exe。

提醒一下,如果您使用的是 Python 3,这将是字节,因此您可能想要out.decode()转换为字符串。


小智 5

同时使用 ' 和 " 对我很有用(Windows 10,python 3)

import os
os.system('"some cmd command here"')
Run Code Online (Sandbox Code Playgroud)

例如打开我的网络浏览器我可以使用这个:

os.system('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"')
Run Code Online (Sandbox Code Playgroud)

(编辑)为了更简单地打开浏览器,我可以使用这个:

import webbrowser
webbrowser.open('website or leave it alone if you only want to open the 
browser')
Run Code Online (Sandbox Code Playgroud)