[英]Problem with capaturing Python output from a Python script containing subprocess.call()
這是我的問題。 嘗試捕獲 Python 輸出時, subprocess.call() 輸出錯誤地出現在 print() 輸出之前。 我在 Windows 10 上使用 Python 3.7.2 從命令窗口運行 Python。
這是一個說明問題的小例子:
import subprocess
print("test")
subprocess.call("where python",shell=True)
請注意,print() 輸出應該在 subprocess.call() 輸出之前。
這是我在不捕獲輸出的情況下運行時得到的結果:
c:\Users\GeoffAlexander\Documents\Python>python test.py
test
C:\Users\GeoffAlexander\AppData\Local\Programs\Python\Python37-32\python.exe>
c:\Users\GeoffAlexander\Documents\Python>
print() 輸出按預期正確出現在 subprocess.call() 輸出之前。
但是,當我將輸出重定向到文件時,我得到的是:
c:\Users\GeoffAlexander\Documents\Python>python test.py > test.out
c:\Users\GeoffAlexander\Documents\Python>cat test.out
C:\Users\GeoffAlexander\AppData\Local\Programs\Python\Python37-32\python.exe
test
c:\Users\GeoffAlexander\Documents\Python>
請注意, subprocess.call() 輸出錯誤地出現在 print() 輸出之前。
為什么會發生這種情況? 如何以正確的順序捕獲 Python 輸出?
如何以正確的順序捕獲 Python 輸出?
你好,
好吧,嘗試在打印調用后刷新標准輸出,例如:
import subprocess
import sys
print("test")
sys.stdout.flush()
subprocess.call("echo python",shell=True)
輸出將是正確的(在 Linux 系統上測試):
$ python test.py
test
python
$ python test.py > filename
$ cat filename
test
python
您需要通過管道與子進程通信
有關示例,請參見https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.