1

我正在编写一个脚本,通过使用适当的“版本”命令行标志(即--version、-v 等)从命令行程序获取版本号。整个程序使用正则表达式从文本中获取实际版本号输出,然后将其与从 xml conf 文件等中提取的最小要求或最大允许版本的各种条件进行比较。

该脚本运行良好,直到执行 bzip2。

对于大多数程序,以下代码没有问题:

args = 'cmd --version'

output = subprocess.getstatusoutput(args)

切得很干。然而!如果您尝试使用 bzip2(到目前为止这是我遇到问题的唯一程序)ala 'bzip2 --version' python "freezes" 并且您必须 ctrl-C 才能在没有记录输出的情况下中断当然。

我尝试了各种变化,例如走长路,即:

import subprocess
from subprocess import PIPE, STDOUT

proc = subprocess.Popen(args, stdout=PIPE, stderr=STDOUT)
while(True):
    code = proc.poll()
    if(code is not None):
        break
    line = proc.stdout.readline() # or even read()
    etc.

无论我使用哪种方法来提取相关文本,Python 总是在某个点之后挂起。我在某些时候尝试过 .kill() 来阻止锁定事件,但无济于事。

我认为它只是使用 bzip2 ,因为出于某种原因,它仍然期待带有 --version 标志的输入。

有什么想法吗?

4

2 回答 2

0

My bzip2 is not expecting input even with --version, and you can test that easily for yourself by just running the command.

This code works for me on Python 2.4-3.2:

import subprocess
from subprocess import PIPE, STDOUT

import sys
proc = subprocess.Popen(sys.argv[1:], stdout=PIPE, stderr=STDOUT)
while True:
    line = proc.stdout.readline() # or even read()
    while True:
        line = proc.stdout.readline() # or even read()
        if not line:
            break
        print(line)
    code = proc.poll()
    if(code is not None):
        break

No hanging of any kind. I can even run vi foo.py with it. Obviously that doesn't work very well as vi suddenly doesn't have a terminal to talk to, but I get no hanging. Doing :q! will quite vi as usual. So if your bzip2 expects input, just input something and it will continue. If this works, then that is the problem.

于 2011-05-28T11:53:21.357 回答
0

编码:

import subprocess
from subprocess import STDOUT,PIPE

proc = subprocess.Popen(("bunzip2","--version"),stdout=PIPE,stderr=STDOUT)
data = proc.stdout.read()
print data

现在适用于 bzip2 1.0.6(或 bunzip2 1.0.6,但它们是同一个应用程序)。在我看来,这真的像 bzip2 中的一个错误...... --version 应该打印版本并退出,而不是尝试读/写到标准输入。

于 2011-05-28T01:14:11.483 回答