Sub Process在自己的Thread中

时间:2011-09-28 12:58:04

标签: python multithreading python-3.x

我想知道以下课是否合理。我正在使用它在我的测试环境中为每个测试启动一堆模拟器。

    class SubProcessInOwnThread(threading.Thread):
        def __init__(self, arguments, currentWorkingDirectory):
            self.arguments = arguments
            self.currentWorkingDirectory = currentWorkingDirectory
            threading.Thread.__init__(self)
            self.isTerminated = False

        def run(self):
            try:
                self.subProcess = subprocess.Popen(self.arguments, cwd=self.currentWorkingDirectory)
                self.subProcess.wait()
            finally:
                self.isTerminated = True

        def kill(self):
            while not self.isTerminated:
                try:
                    self.subProcess.kill()
                except:
                    time.sleep(0.1)

一些表达方式:

    # Normal
    subProcessThreadArguments = ["cmd.exe"]
    subProcessThread = SubProcessInOwnThread(subProcessThreadArguments,r"C:\\")
    subProcessThread.start()
    time.sleep(5)
    subProcessThread.kill()

    # Process killed very quickly
    subProcessThreadArguments = ["cmd.exe"]
    subProcessThread = SubProcessInOwnThread(subProcessThreadArguments,r"C:\\")
    subProcessThread.start()
    subProcessThread.kill()

    # Incorrect configuration
    subProcessThreadArguments = ["cmdsfgfg.exe"]
    subProcessThread = SubProcessInOwnThread(subProcessThreadArguments,r"C:\\")
    subProcessThread.start()
    time.sleep(5)
    subProcessThread.kill()

所以我可以创建这样的模拟器:

    subProcessThreadArguments1 = ["sim1.exe"]
    subProcessThread1 = SubProcessInOwnThread(subProcessThreadArguments1,r"C:\\")
    subProcessThread1.start()

    subProcessThreadArguments2 = ["sim2.exe"]
    subProcessThread2 = SubProcessInOwnThread(subProcessThreadArguments2,r"C:\\")
    subProcessThread2.start()

    # do test...

    subProcessThread1.kill()
    subProcessThread2.kill()

我对任何改进都感兴趣。我应该考虑使用with关键字吗?如果是这样,那么好处是什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

我没有看到在wait()这里有一个单独的线程被卡住了。直接在子流程上工作就像

一样
class SubProcessWithoutThread(object):
    def __init__(self, arguments, currentWorkingDirectory):
        self.arguments = arguments
        self.currentWorkingDirectory = currentWorkingDirectory
        self.isTerminated = False

    def start(self):
        self.subProcess = subprocess.Popen(self.arguments, cwd=self.currentWorkingDirectory)

    def kill(self):
        while self.subProcess.poll() is None:
            try:
                self.subProcess.kill()
            except:
                time.sleep(0.1)

    __enter__ = start
    def __exit__(self, *x):
        self.kill()

(未测试的)

我已经为上下文管理器添加了方法,但是我看不出它会如何帮助你,因为它必须创建很多with语句,包括必要的缩进。

但也许我错了你的意图......