簡體   English   中英

如何在 Python 中啟動、監視和終止進程

[英]How to launch, monitor and kill a process in Python

我需要能夠在 Python 中啟動一個長時間運行的進程。 在進程運行時,我需要將 pipe output 到我的 Python 應用程序以在 UI 中顯示它。 UI 還需要能夠終止進程。

我做了很多研究。 但我還沒有找到一種方法來完成這三件事。

subprocess.popen() 讓我啟動一個進程並在需要時終止它。 但它不允許我查看它的 output,直到該過程完成。 我監控的過程永遠不會自行完成。

os.popen() 讓我啟動一個進程並在它運行時監控它的 output。 但我不知道有什么方法可以殺死它。 我通常在 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)

提前致謝。

我建議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()
  • stdoutstderr kwargs 設置為subprocess.PIPE允許您通過.communicate讀取相應的流,而不是將它們打印到父流中(因此它們會出現在您運行腳本的終端中)
  • .kill()允許您隨時終止進程
  • 可以隨時通過readline()查詢process.stdoutprocess.stderr以獲取它們的當前行,或者通過read()readlines()獲取任意數量的緩沖區內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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