[英]python subprocess.call output is not interleaved
我有一个运行其他Shell脚本的python(v3.3)脚本。 我的python脚本还显示“关于要运行脚本X”和“完成运行脚本X”之类的消息。
当我运行脚本时,我将所有shell脚本的输出与我的打印语句分开。 我看到这样的事情:
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
运行外壳程序脚本的代码如下所示:
print( "running command: " + cmnd )
ret_code = subprocess.call( cmnd, shell=True )
print( "done running command")
我写了一个基本的测试脚本, 做 *不*看到此行为。 这段代码符合我的期望:
print("calling")
ret_code = subprocess.call("/bin/ls -la", shell=True )
print("back")
关于为什么不交错输出的任何想法?
谢谢。 此方法有效,但有一个限制-在命令完成之前,您将看不到任何输出。 我从另一个使用popen的问题( 这里 )中找到了答案,还可以让我实时查看输出。 这就是我最终得到的结果:
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,并允许我查看调用脚本的进度。
它与STDOUT和STDERR缓冲有关。 您应该使用subprocess.Popen
将STDOUT
和STDERR
从子进程重定向到应用程序中。 然后,根据需要输出它们。 例:
import subprocess
cmd = ['ls', '-la']
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, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process.wait() # Wait for the underlying process to complete.
out, err = process.communicate() # Capture what it outputted on STDOUT and STDERR
errcode = process.returncode # Harvest its returncode, if needed.
print(out)
print('done running command')
另外,除非确实需要,否则我不会使用shell = True
。 它迫使子进程仅运行命令就启动整个外壳环境。 通常最好直接注入Popen的env参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.