Python读取Windows命令行输出

标签 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

最佳答案

以下代码有效。我需要传递 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读取Windows命令行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079754/

相关文章:

python - 在 SQLite 数据库中输入大量条目

python - 在引号内使用引号

python - 为什么我可以在 Python 的抽象类中访问派生类的变量?

linux - Linux 中的打印机 Api

python - 无法在 python 上运行转义的 Windows 命令行

git describe 只显示最新的标签和额外的提交

python - scipy 多个数组的并行插值

windows - wix:卸载使用服务的应用程序需要重新启动?

windows - 你知道 Windows 上的 wc(unix 字数统计命令)的类似程序吗?

java - 使用 jar 和文本文件输入运行 java 文件