问题描述
我有一个运行其他 shell 脚本的 python (v3.3) 脚本.我的 python 脚本还打印诸如关于运行脚本 X"和完成运行脚本 X"之类的消息.
I have a python (v3.3) script that runs other shell scripts. My python script also prints message like "About to run script X" and "Done running script X".
当我运行我的脚本时,我将 shell 脚本的所有输出与我的打印语句分开.我看到的是这样的:
When I run my script I'm getting all the output of the shell scripts separate from my print statements. I see something like this:
All of script X's output
All of script Y's output
All of script Z's output
About to run script X
Done running script X
About to run script Y
Done running script Y
About to run script Z
Done running script Z
我运行 shell 脚本的代码如下所示:
My code that runs the shell scripts looks like this:
print( "running command: " + cmnd )
ret_code = subprocess.call( cmnd, shell=True )
print( "done running command")
我写了一个基本的测试脚本并且做 *没有*看到这种行为.这段代码符合我的预期:
I wrote a basic test script and do *not* see this behaviour. This code does what I would expect:
print("calling")
ret_code = subprocess.call("/bin/ls -la", shell=True )
print("back")
知道为什么不交错输出的原因吗?
Any idea on why the output is not interleaved?
推荐答案
谢谢.这有效,但有一个限制 - 在命令完成之前您看不到任何输出.我从另一个问题(此处)中找到了答案,该问题使用popen 还可以让我实时查看输出.这是我最终的结果:
Thanks. This works but has one limitation - you can't see any output until after the command completes. I found an answer from another question (here) that uses popen but also lets me see the output in real time. Here's what I ended up with this:
import subprocess
import sys
cmd = ['/media/sf_git/test-automation/src/SalesVision/mswm/shell_test.sh', '4', '2']
print('running command: "{0}"'.format(cmd)) # output the command.
# Here, we join the STDERR of the application with the STDOUT of the application.
process = subprocess.Popen(cmd, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
line = line.replace('\n', '')
print(line)
sys.stdout.flush()
process.wait() # Wait for the underlying process to complete.
errcode = process.returncode # Harvest its returncode, if needed.
print( 'Script ended with return code of: ' + str(errcode) )
这使用 Popen 并允许我查看被调用脚本的进度.
This uses Popen and allows me to see the progress of the called script.
这篇关于python subprocess.call 输出不是交错的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!