我有一个运行其他 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
Run Code Online (Sandbox Code Playgroud)
我运行 shell 脚本的代码如下所示:
print( "running command: " + cmnd )
ret_code = subprocess.call( cmnd, shell=True )
print( "done running command")
Run Code Online (Sandbox Code Playgroud)
我写了一个基本的测试脚本,但*没有*看到这种行为。这段代码符合我的期望:
print("calling")
ret_code = subprocess.call("/bin/ls -la", shell=True )
print("back")
Run Code Online (Sandbox Code Playgroud)
关于为什么不交错输出的任何想法?
谢谢。这有效,但有一个限制 - 在命令完成之前您看不到任何输出。我从另一个问题(这里)中找到了一个答案,该问题使用 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) )
Run Code Online (Sandbox Code Playgroud)
这使用 Popen 并允许我查看被调用脚本的进度。
| 归档时间: |
|
| 查看次数: |
758 次 |
| 最近记录: |