在后台启动另一个进程并用Python捕获输出

2024-07-01 06:53:14 发布

您现在位置:Python中文网/ 问答频道 /正文

在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。在


Tags: self进程defstdoutprocpidthread后台
2条回答

删除shell=True后,它开始工作。并重新构造了没有线程的代码。如果我添加shell=True,那么它在communicate调用中再次开始阻塞。在

proc = subprocess.Popen(["./cmd.py"], stdout=subprocess.PIPE)
#Do something else
sleep(2)
os.system('kill -15 ' + str(proc.pid))
print 'Killed ' + str(proc.pid)
print 'cmd out: ' + proc.communicate()[0]
print 'finished'

Here is a good explaination of shell=True

将shell参数设置为true值会导致子进程生成一个中间shell进程,并告诉它运行命令

总是使用=shell=False,但是您的代码在我的linux环境中运行如下,为了简单起见,我使用shell文件作为命令来运行]:

import os,signal
import time
import subprocess
from threading import Thread

g_flag = 0
class StartChecking(Thread):
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        global g_flag
        print 'Starting thread'
        proc = subprocess.Popen(["./a.sh"], stdout=subprocess.PIPE, shell=True)
        pid = proc.pid
        print 'Sniff started ' + str(pid)
        if (pid != 0) and (pid != 1):
            while g_flag == 0:
                time.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
time.sleep(5)
g_flag = 1
th.join()
print 'thread joined'

相关问题 更多 >

    热门问题