【问题标题】:Python read windows Command Line outputPython读取windows命令行输出
【发布时间】:2013-11-19 18:57:25
【问题描述】:

我正在尝试在 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 中输入该命令会发生什么?

标签: python windows command-line


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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

    【讨论】:

    • 使用 output = commands.getstatusoutput(cmd) 给了我(1,“'{' 不被识别为内部或外部命令,\不可运行的程序或批处理文件。”)
    • 也不会触发批处理文件 cobuild 存档。
    • 你的cobuild archive 是一个可执行文件吗?,检查这个尝试从command prompt 运行相同(在同一目录中),如果它仍然抛出错误,问题出在你的可执行文件上! !
    • 是的。如果我只是从命令提示符运行 cobuild archive,它运行良好。我已经在命令行中使用该命令很长时间了。可执行文件不是问题。它是我的 python 代码。
    • 然后在您的subprocess 调用中尝试cmd = ["cobuild", "archive"],并将此cmd 传递给您的子进程
    【解决方案3】:

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

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

    更新:

    命令模块在 Python 3 中已被移除,因此这仅适用于 Python 2。

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

    【讨论】:

    • 问题不在于控制台读取,而在于执行本身
    • 请发布类似“您介意发布带有正确缩进的代码吗?”之类的内容。作为评论,或者只是编辑原始帖子 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2013-12-26
    相关资源
    最近更新 更多