Python實時獲取外部程式輸出結果

如何Python實時獲取外部程式輸出結果,可以在執行時加上-u引數或者在print函式中使用flush=True

下面寫兩個指令碼驗證一下是否可行。

system_time。py

獲取系統時間,每秒列印一次,共列印3次

# !/usr/bin/python3# -*- coding: utf-8 -*-import datetimeimport timefor line in range(0, 3): print(datetime。datetime。now()。strftime(“%H:%M:%S”)) if line == 2: break time。sleep(1)

執行結果

Python實時獲取外部程式輸出結果

result_output。py

使用subprocess。Popen執行啟動system_time。py檔案命令

# !/usr/bin/python3# -*- coding: utf-8 -*-import subprocessres = subprocess。Popen([“/usr/bin/python3 /root/system_time。py”], shell=True, stdout=subprocess。PIPE, stderr=subprocess。PIPE)while res。poll() is None: print(res。stdout。readline())

執行結果

Python實時獲取外部程式輸出結果

執行result_output。py發現並沒有實時的逐行列印,那加上-u引數試一下

# !/usr/bin/python3# -*- coding: utf-8 -*-import subprocessres = subprocess。Popen([“/usr/bin/python3 -u /root/system_time。py”], shell=True, stdout=subprocess。PIPE, stderr=subprocess。PIPE)while res。poll() is None: print(res。stdout。readline())

執行結果

Python實時獲取外部程式輸出結果

加上-u後可以實時列印了,在看一下在print函式中加上flush=True的效果

首先要在result_output。py檔案中去掉-u引數,然後在system_time。py檔案的print函式中加上flush=True

result_output。py檔案內容

# !/usr/bin/python3# -*- coding: utf-8 -*-import subprocessres = subprocess。Popen([“/usr/bin/python3 /root/system_time。py”], shell=True, stdout=subprocess。PIPE, stderr=subprocess。PIPE)while res。poll() is None: print(res。stdout。readline())

system_time。py檔案內容

# !/usr/bin/python3# -*- coding: utf-8 -*-import datetimeimport timefor line in range(0, 3): print(datetime。datetime。now()。strftime(“%H:%M:%S”)) if line == 2: break time。sleep(1)

執行結果:

Python實時獲取外部程式輸出結果