簡體   English   中英

python subprocess.call輸出未交錯

[英]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.PopenSTDOUTSTDERR從子進程重定向到應用程序中。 然后,根據需要輸出它們。 例:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM