Niy*_*jan 9 python subprocess python-3.x
我正在使用python脚本运行进程subprocess.Popen,同时将输出存储在文本文件中,并在控制台上打印.这是我的代码:
result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in result.stdout.readlines(): #read and store result in log file
openfile.write("%s\n" %line)
print("%s" %line)
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,但它的作用是首先完成该过程并将输出存储在结果变量中.之后for循环存储输出并打印它.
但我希望在运行时输出(因为我的过程可能需要数小时才能完成,所有这些时间都没有得到任何输出).
那么有没有任何其他函数可以动态地(在运行时)给我输出,意味着只要进程给出第一行,就应该打印出来.
这里的问题是.readlines()在返回之前获取整个输出,因为它构造了一个完整的列表.直接迭代:
for line in result.stdout:
print line
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13402 次 |
| 最近记录: |