使用python,我想要並行啓動兩個子進程。一個將啓動一個HTTP服務器,而其他將開始另一個程序(這是由硒IDE插件生成打開Firefox,瀏覽到一個網站,做一些互動python腳本)的執行。另一方面,當第二個子進程完成執行時,我想停止執行第一個子進程(HTTP Server)。使用主Python腳本中的子進程並行執行2個獨立的Python腳本
我的代碼的邏輯是,硒腳本將打開一個網站。該網站將自動對我的HTTP服務器進行幾次GET調用。在selenium腳本完成執行後,應該關閉HTTP Server,以便它可以將所有捕獲的請求記錄在文件中。
這裏是我的代碼:
class Myclass(object):
HTTPSERVERPROCESS = ""
def startHTTPServer(self):
print "********HTTP Server started*********"
try:
self.HTTPSERVERPROCESS=subprocess.Popen('python CustomSimpleHTTPServer.py', \
shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
self.HTTPSERVERPROCESS.communicate()
except Exception as e:
print "Exception captured while starting HTTP Server process: %s\n" % e
def startNavigatingFromBrowser(self):
print "********Opening firefox to start navigation*********"
try:
process=subprocess.Popen('python navigationScript.py', \
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process.communicate()
process.wait()
except Exception as e:
print "Exception captured starting Browser Navigation process : %s\n" % e
try:
if process.returncode==0:
print "HTTPSERVEPROCESS value: %s" % self.HTTPSERVERPROCESS.returncode
print self.HTTPSERVERPROCESS
self.HTTPSERVERPROCESS.kill()
#print "HTTPSERVEPROCESS value: %s" % self.HTTPSERVERPROCESS.returncode
except Exception as e:
print "Exception captured while killing HTTP Server process : %s\n" % e
def startCapture(self):
print "********Starting Parallel execution of Server initiation and firefox navigation script*********"
t1 = threading.Thread(target=self.startHTTPServer())
t2 = threading.Thread(target=self.startNavigatingFromBrowser())
t1.start()
t2.start()
t2.join()
注:開始執行調用startCapture()
的問題是,我得到我的終端在運行上面的代碼
********Starting Parallel execution of HTTP Server initiation and firefox navigation script*********
********HTTP Server started*********
********Opening firefox to start navigation*********
Process finished with exit code 0
以下
我的程序執行完畢即使線程開始爲startNavigatingFromBrowser()仍然有效。即使在我的程序中出現「處理完成退出代碼0」後,我仍然可以看到Firefox瀏覽了網站。由於這個我不能在我的瀏覽器導航線程執行完畢**檢測(這是必要的,因爲我使用process.returncode從navigationScript子回到殺了我的HTTP Server進程)**。
我應該做的代碼什麼樣的變化,這樣,當硒導航子進程執行完畢,這樣我可以阻止我的HTTP服務器,我可以成功檢測?
現在好運嗎?我用wait()調用複製了結構,它適用於我。 –