简体   繁体   English

如何在 Python 中启动、监视和终止进程

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

I need to be able to launch a long-running process in Python.我需要能够在 Python 中启动一个长时间运行的进程。 While the process is running, I need to pipe the output to my Python app to display it in the UI.在进程运行时,我需要将 pipe output 到我的 Python 应用程序以在 UI 中显示它。 The UI needs to also be able to kill the process. UI 还需要能够终止进程。

I've done a lot of research.我做了很多研究。 But I haven't found a way to do all three of those things.但我还没有找到一种方法来完成这三件事。

subprocess.popen() lets me start a process and kill it if I need to. subprocess.popen() 让我启动一个进程并在需要时终止它。 But it doesn't allow me to view its output until the process has finished.但它不允许我查看它的 output,直到该过程完成。 And the process I am monitoring never finishes on its own.我监控的过程永远不会自行完成。

os.popen() lets me start a process and monitor its output as it is running. os.popen() 让我启动一个进程并在它运行时监控它的 output。 But I don't know of a way to kill it.但我不知道有什么方法可以杀死它。 I'm usually in the middle of a readline() call.我通常在 readline() 调用中。

When using os.popen(), is there a way to know if there is any data in the buffer before calling read() or readline?使用 os.popen() 时,有没有办法在调用 read() 或 readline 之前知道缓冲区中是否有任何数据? For example...例如...

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)

Thanks in advance.提前致谢。

I'd recommend subprocess.Popen for fine-grained control over processes.我建议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()
  • Setting stdout and stderr kwargs to subprocess.PIPE allows you to read the respective streams via .communicate instead of having them be printed to the parent's streams (so they'd appear in the terminal you ran the script in)stdoutstderr kwargs 设置为subprocess.PIPE允许您通过.communicate读取相应的流,而不是将它们打印到父流中(因此它们会出现在您运行脚本的终端中)
  • .kill() allows you to terminate the process whenever you want .kill()允许您随时终止进程
  • process.stdout and process.stderr can be queried at any time to obtain their current line, via readline() , or an arbitrary amount of buffer content via read() or readlines()可以随时通过readline()查询process.stdoutprocess.stderr以获取它们的当前行,或者通过read()readlines()获取任意数量的缓冲区内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM