【问题标题】:How to launch, monitor and kill a process in Python如何在 Python 中启动、监视和终止进程
【发布时间】:2022-01-19 17:43:09
【问题描述】:

我需要能够在 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)

提前致谢。

【问题讨论】:

    标签: python multithreading process popen


    【解决方案1】:

    我建议使用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() 允许您随时终止进程
    • 可以随时查询process.stdoutprocess.stderr 以获取它们的当前行,通过readline(),或通过read()readlines() 获得任意数量的缓冲区内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      相关资源
      最近更新 更多