Sub Process in its own Thread
我想知道下节课是否好。我正在使用它为我的测试环境中的每个测试启动一组模拟器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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) |
一些萨纳里奥斯:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # 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() |
所以我可以创建这样的模拟器:
1 2 3 4 5 6 7 8 9 10 11 12 | 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() |
我对任何改进都感兴趣。我应该考虑使用关键字吗?如果是这样,会有什么好处呢?
谢谢!
我不认为这里有一条单独的线被卡在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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() |
(未经测试)
我已经为一个上下文管理器添加了方法,但是我看不出这将如何帮助您,因为这将是一堆您必须创建的
但也许我把你的意图搞错了…