在python中,我想启动另一个python脚本作为后台进程,几秒钟后,我需要终止这个派生的进程,并将stdout放入一个变量中。在
我尝试使用subprocess.Popen
,我可以作为后台进程生成并在几秒钟后终止。但至少在将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'
输出是
^{pr2}$注意:在ubuntu 16.04
中使用Python 2.7.12
。在
删除
shell=True
后,它开始工作。并重新构造了没有线程的代码。如果我添加shell=True
,那么它在communicate
调用中再次开始阻塞。在Here is a good explaination of shell=True
将shell参数设置为true值会导致子进程生成一个中间shell进程,并告诉它运行命令
总是使用=shell=False,但是您的代码在我的linux环境中运行如下,为了简单起见,我使用shell文件作为命令来运行]:
相关问题 更多 >
编程相关推荐