Python读取Windows命令行输出

时间:2013-11-19 18:57:25

标签: python windows command-line

我正在尝试在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 archive并读取它的输出。但是,上面的代码给了我这个错误。

 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

3 个答案:

答案 0 :(得分:2)

以下代码有效。我需要为参数

传递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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

你介意用正确的缩进发布你的代码吗?它们在python中有很大的影响 - 另一种方法是:

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