簡體   English   中英

在后台啟動進程並檢索輸出

[英]Launch process in background and retrieve output

我想在后台啟動Flask應用程序的實例,以便我可以對它運行webdriver測試。 為此我需要捕獲&命令的輸出,這樣我就可以在測試結束時終止進程。

我已經嘗試過subprocess.call()subprocess.check_output()但是我無法捕獲第一個進程號或后者進程與另一個進程號。 我還能嘗試什么?

你可以和Popen一起使用nohup:

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

您可能需要查看Flask-Testing庫,它支持運行燒瓶服務器,因此您可以對其進行selenium測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM