【发布时间】:2018-09-04 15:53:33
【问题描述】:
在 python 中,我想启动另一个 python 脚本作为后台进程,几秒钟后我需要终止生成的进程并将标准输出放入变量中。
我尝试使用subprocess.Popen,我能够作为后台进程生成并在几秒钟后终止。但是 atlast 将 stdout 重定向到一个变量时它被阻塞了。
有人可以建议我修复它吗?或者除了subprocess.Popen 之外还有其他模块可以做到这一点吗?
g_flag = 0
class StartChecking(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
global g_flag
print 'Starting thread'
proc = subprocess.Popen(["./cmd.py"], stdout=subprocess.PIPE, shell=True)
pid = proc.pid
print 'Sniff started ' + str(pid)
if (pid != 0) and (pid != 1):
while g_flag == 0:
sleep(0.1)
os.kill(pid, signal.SIGTERM)
print 'Killed ' + str(pid)
(out, err) = proc.communicate() # Currently its blocking here
print out
th = StartChecking()
th.start()
#Do something else
sleep(5)
g_flag = 1
th.join()
print 'thread joined'
输出是
Starting thread
Sniff started 24294
Killed 24294
注意:在ubuntu 16.04 中使用Python 2.7.12。
【问题讨论】:
-
不要混用线程和fork linuxprogrammingblog.com/…
-
没错。最初我使用的是无线程,后来为了解决该块问题,我尝试了线程。
标签: python python-2.7 stdout spawn