Python:在后台进程上使用popen poll [英] Python: Using popen poll on background process

查看:477
本文介绍了Python:在后台进程上使用popen poll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在后台运行一个很长的进程(实际上是另一个python脚本).我需要知道什么时候结束.我发现Popen.poll()对于后台进程总是返回0.还有另一种方法吗?

I am running a long process (actually another python script) in the background. I need to know when it has finished. I have found that Popen.poll() always returns 0 for a background process. Is there another way to do this?

p = subprocess.Popen("sleep 30 &", shell=True,
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
a = p.poll()
print(a)

以上代码从不打印None.

推荐答案

您无需使用shell后台&语法,因为subprocess会自行在后台运行该进程

You don't need to use the shell backgrounding & syntax, as subprocess will run the process in the background by itself

只需正常运行命令,然后等待Popen.poll返回not None

Just run the command normally, then wait until Popen.poll returns not None

import time
import subprocess

p = subprocess.Popen("sleep 30", shell=True)
# Better: p = subprocess.Popen(["sleep", "30"])

# Wait until process terminates
while p.poll() is None:
    time.sleep(0.5)

# It's done
print "Process ended, ret code:", p.returncode

这篇关于Python:在后台进程上使用popen poll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆