Skip to main content
 首页 » 编程设计

python subprocess.call 输出不交错

2025年05月04日15yxwkf

我有一个运行其他 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 

我运行 shell 脚本的代码如下所示:

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 的问题 ( here ) 中找到了答案,但也让我可以实时查看输出。这是我最终得到的结果:

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 并允许我查看被调用脚本的进度。