Python读取Windows命令行输出

我试图在python中执行一个命令,并在Windows命令行上读取其输出。

到目前为止,我已经写了下面的代码:

def build(): command = "cobuild archive" print "Executing build" pipe = Popen(command,stdout=PIPE,stderr=PIPE) while True: line = pipe.stdout.readline() if line: print line 

我想在命令行执行命令cobuild存档并读取它的输出。 但是,上面的代码给了我这个错误。

  File "E:\scripts\utils\build.py", line 33, in build pipe = Popen(command,stdout=PIPE,stderr=PIPE) File "C:\Python27\lib\subprocess.py", line 679, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 893, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified 

下面的代码工作。 我需要传递shell = True的参数

 def build(): command = "cobuild archive" pipe = Popen(command,shell=True,stdout=PIPE,stderr=PIPE) while True: line = pipe.stdout.readline() if line: print line if not line: break 

WindowsError: [Error 2] The system cannot find the file specified

此错误说明subprocess模块无法找到您的executable(.exe)

这里"cobuild archive"

假设,如果你的可执行文件在这个路径下: "C:\Users\..\Desktop" ,那么,

 import os os.chdir(r"C:\Users\..\Desktop") 

然后使用你的subprocess

你介意把你的代码张贴正确的缩进吗? 它们在python中有很大的作用 – 另一种做法是:

 import commands # the command to execute cmd = "cobuild archive" # execute and get stdout output = commands.getstatusoutput( cmd ) # do something with output # ...