1

有时我需要在我的 python 程序中调用一个 cmd 并想解析输出。在大多数情况下, cmd 调用执行它的操作,打印几行并终止。不幸的是,一些 cmd 命令似乎永远不会终止并继续打印空白行。因此,我开始计算读取的行数,然后在某个点停止。示例代码:

from subprocess import Popen
from subprocess import PIPE
from subprocess import STDOUT

command = ["gcc", "-v"]

try:
    process = Popen(command, bufsize=1, universal_newlines=True, stdout=PIPE, stderr=STDOUT)

    if process.returncode:
        print("Cmd command {} was spawned successfully, yet an error occuring during the execution of the command".format(command))

    lineCounter = 0
    for line in iter(process.stdout.readline, ''):
         if(lineCounter < 50):
             print(line)
             lineCounter += 1
         else:
             break

except Exception as exceptionError:
     print("Command {} can't be started. Error message: {}".format(command, exceptionError))

虽然“gcc -v”实际上终止了,但我遇到的其他一些命令却没有。有没有更优雅和稳定的方法来解决这个问题?我读了一些建议,在一段时间后停止解析而不是行,但这对我来说似乎也有点脏。

4

1 回答 1

-1
lineCounter = 0
prevLine = ''
for line in iter(process.stdout.readline, ''):
     print(line)
     if line == prevLine:
         lineCounter += 1
         if lineCounter > 50:
             break
     else:
         prevLine = line
         lineCounter = 0
于 2020-01-20T08:27:34.677 回答