Python 在后台启动进程并检索输出

Python 在后台启动进程并检索输出,python,python-2.7,subprocess,Python,Python 2.7,Subprocess,我想在后台启动我的Flask应用程序的一个实例,这样我就可以在上面运行webdriver测试。为此,我需要捕获&命令的输出,以便在测试结束时终止进程 我已经尝试了子流程.call(),和子流程。检查输出(),但我无法捕捉到第一个流程的流程号,也无法捕捉到另一个流程的后台。我还可以尝试什么?您可以将nohup与Popen一起使用: from subprocess import Popen, check_call from os import devnull p = Popen(["nohup"

我想在后台启动我的Flask应用程序的一个实例,这样我就可以在上面运行webdriver测试。为此,我需要捕获
&
命令的输出,以便在测试结束时终止进程


我已经尝试了
子流程.call()
,和
子流程。检查输出()
,但我无法捕捉到第一个流程的流程号,也无法捕捉到另一个流程的后台。我还可以尝试什么?

您可以将nohup与Popen一起使用:

from subprocess import Popen, check_call

from os import devnull

p = Popen(["nohup", "python", "test.py"], stdout=open(devnull, "w"))

import time

print(p.pid)
for i in range(3):
    print("In for")
    time.sleep(1)

check_call("ps -ef | grep {} | grep -v grep".format(p.pid), shell=True)
p.terminate()
check_call("ps -ef | grep {} | grep -v grep".format(p.pid), shell=True)
test.py:

import  time
while True:
    time.sleep(1)
    print("Still alive")
输出:

In [3]: from os import devnull

In [4]: p = Popen(["nohup", "python", "b.py"], stdout=open(devnull, "w"))
nohup: ignoring input and redirecting stderr to stdout
In [5]: print(p.pid)
28332

In [6]: for i in range(3):
   ...:         print("In for")
   ...:         time.sleep(1)
   ...:     
In for
In for
In for

In [7]: check_call("ps -ef | grep {} | grep -v grep".format(p.pid), shell=True)
padraic  28332 28301  1 20:55 pts/8    00:00:00 python test.py 
Out[7]: 0

In [8]: p.terminate()

In [9]: check_call("ps -ef | grep {} | grep -v grep".format(p.pid), shell=True)
padraic  28332 28301  0 20:55 pts/8    00:00:00 [python] <defunct>
Out[9]: 0
[3]中的
:从操作系统导入devnull
在[4]中:p=Popen([“nohup”、“python”、“b.py”],stdout=open(devnull,“w”))
nohup:忽略输入并将stderr重定向到stdout
In[5]:打印(p.pid)
28332
[6]中:对于范围(3)中的i:
…:打印(“In for”)
时间。睡眠(1)
...:     
等待
等待
等待
[7]中的check|u调用(“ps-ef | grep{}| grep-vgrep.”格式(p.pid),shell=True)
padraic 28332 283011 20:55 pts/8 00:00:00 python test.py
Out[7]:0
在[8]:p.terminate()中
[9]中的check|u调用(“ps-ef | grep{}| grep-vgrep.”格式(p.pid),shell=True)
padraic 28332 283010 20:55分/8 00:00:00[python]
Out[9]:0

您可能想看看这个库,它支持运行flask服务器,因此您可以对它进行selenium测试

你看过吗?嗯。把它变成一个答案,我会接受的。很高兴这对你有用!完成。Popen是否已弃用?@ruipacheco,os.Popen,而不是subprocess.Popen,99%的子流程使用Popen