[英]Python subprocess interaction, why does my process work with Popen.communicate, but not Popen.stdout.read()?
[英]Python - Using Popen.communicate() does not capture the stdout and stderr of a system call as expected
我有一個執行系統調用的Python腳本(該調用實際上是一個java
程序)。 我正在使用Popen.communicate()
嘗試捕獲stdout
和stderr
。 但是,它僅適用於某些Java
應用程序(我直接調用的所有java
應用程序在外殼程序中直接執行時都會在屏幕上顯示某些內容)。
我使用的代碼如下:
# Perform the java call
try:
p = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError as e:
error_msg = ' Error reading file while executing system command: {0}'.format(e.message)
except ValueError as e:
error_msg = ' Error in arugments while executing system command: {0}'.format(e.message)
else:
# Display the results in real time
for line in iter(p.stdout.readline, ''):
sys.stdout.write(line)
# Grab the stdout and stderr from the process.
output, err = p.communicate()
finally:
# Check to see if an internal error occurred. If not, flip the flag
if not err and not error_msg:
java_completed = True
else:
java_completed = False
在某些情況下,永遠不會調用sys.stdout.write(line)
,而在其他情況下則不會調用。
有人對這個有經驗么?
我注意到的第一件事是,您正在從流程標准輸出中讀取所有內容,然后嘗試進行p.communicate()
communicate
:您已經從管道中讀取了所有內容,因此p.communicate()
的output
結果將始終為空。
但這不能解釋為什么有時不調用sys.stdout.write
。
要記住的一件事是,有多種方法可以在控制台(即命令窗口)中顯示內容。 打印到流程stdout流只是一種方法,這就是您可以使用以上代碼捕獲的方法。 如果我從Java時代回想起,有時會使用某種類型的Console
類來顯示到控制台,但這可能不使用stdout。 此外,高級控制台顯示庫(例如curses
通常不寫入stdout,它們直接與控制台對象交互。 我不知道如何或者是否可以從這些類型的過程中捕獲輸出,但是如果可能的話,它可能是非常特定於系統的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.