繁体   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