Python read windows命令行输出

2024-06-06 18:15:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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

Tags: 代码命令行inpybuildstdoutlinecommand
3条回答

以下代码有效。我需要为参数传递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

你介意把你的代码和正确的缩进一起寄出去吗?它们在python中有很大的作用-另一种方法是:

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

更新:

在Python 3中,commands模块已经被删除,因此这只是Python 2的解决方案。

https://docs.python.org/2/library/commands.html

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

相关问题 更多 >