【问题标题】:Launch process in background and retrieve output在后台启动进程并检索输出
【发布时间】:2016-04-06 19:20:40
【问题描述】:

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

我已经尝试过subprocess.call()subprocess.check_output(),但我无法捕捉到第一个进程的编号或与另一个进程在后台运行。我还能尝试什么?

【问题讨论】:

  • 你看过Flask-Testing吗?
  • 呃。把它变成一个答案,我会接受的。
  • 很高兴为您工作!完成。

标签: python python-2.7 subprocess


【解决方案1】:

您可能想查看Flask-Testing 库,它支持运行您的烧瓶服务器,因此您可以针对它进行硒测试。

【讨论】:

    【解决方案2】:

    您可以将 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
    

    【讨论】:

    • Popen 没有被弃用吗?
    • @ruipacheco,os.Popen,不是 subprocess.Popen,99% 的子进程使用 Popen
    最近更新 更多