我需要能夠在 Python 中啟動一個長時間運行的行程。在行程運行時,我需要將輸出通過管道傳輸到我的 Python 應用程式以在 UI 中顯示它。UI 還需要能夠終止行程。
我做了很多研究。但我還沒有找到一種方法來完成這三件事。
subprocess.popen() 讓我啟動一個行程并在需要時終止它。但它不允許我在該程序完成之前查看其輸出。我正在監控的程序永遠不會自行完成。
os.popen() 讓我啟動一個行程并在它運行時監控它的輸出。但我不知道有什么方法可以殺死它。我通常在 readline() 呼叫的中間。
使用 os.popen() 時,有沒有辦法在呼叫 read() 或 readline 之前知道緩沖區中是否有任何資料?例如...
output = os.popen(command)
while True:
# Is there a way to check to see if there is any data available
# before I make this blocking call? Or is there a way to do a
# non-blocking read?
line = output.readline()
print(line)
提前致謝。
uj5u.com熱心網友回復:
我建議使用subprocess.Popen對流程進行細粒度控制。
import subprocess
def main():
try:
cmd = ['ping', '8.8.8.8']
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
text=True
)
while True:
print(process.stdout.readline().strip())
except KeyboardInterrupt:
print('stopping process...')
process.kill()
if __name__ == '__main__':
main()
- 設定
stdout和stderrkwargssubprocess.PIPE允許您通過讀取相應的流.communicate而不是將它們列印到父流中(因此它們會出現在您運行腳本的終端中) .kill()允許您隨時終止行程process.stdout并且process.stderr可以隨時查詢以獲取其當前行、viareadline()或任意數量的緩沖區內容,通過read()或readlines()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/391061.html
上一篇:由WindowsFormsSynchronizationContext和System.Events.UserPreferenceChanged引起的UI凍結
