使用来自主 Python 脚本的子进程并行执行 2 个单独的 Python 脚本

Parallel execution of 2 separate Python scripts using subprocess from the main Python script

使用Python,我想并行启动两个子进程。一个将启动一个 HTTP 服务器,而另一个将开始执行另一个程序(这是一个由 Selenium IDE 插件生成的 Python 脚本,用于打开 Firefox,导航到网站,并进行一些交互)。另一方面,我想在第二个子进程执行完毕后停止执行第一个子进程(HTTP 服务器)。

我的代码逻辑是 Selenium 脚本将打开一个网站。该网站将自动对我的 HTTP 服务器进行一些 GET 调用。 Selenium 脚本执行完毕后,应该关闭 HTTP 服务器,以便它可以将所有捕获的请求记录在一个文件中。

这是我的代码:

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() 启动的线程仍处于活动状态,我的程序仍会完成执行。我可以看到 Firefox 正在浏览网站,即使我的程序出现“进程已完成,退出代码为 0”。因此,我无法检测到我的浏览器导航线程何时完成执行。 (这是必要的,因为我正在使用从 navigationScript 子进程返回的 process.returncode 来终止我的 HTTP 服务器进程).

我应该对代码进行哪些更改才能成功检测到 Selenium 导航子进程何时完成执行,从而停止我的 HTTP 服务器?

在退出程序之前调用 t2.join()。这会等待导航线程终止,然后继续执行。

编辑:

您的导航线程立即终止,因为您没有等待子进程退出。这应该可以解决问题:

process=subprocess.Popen('python navigationScript.py', \
                        shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process.wait()

这将暂停线程,直到子进程完成。