1
我想知道下面的類是否健全。我正在使用它爲我的測試環境中的每個測試啓動一堆模擬器。子過程在自己的線程
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)
一些senarios:
# 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()
我很感興趣的任何improvents。我應該考慮使用with關鍵字嗎?如果是這樣,這個好處是什麼?
謝謝!
感謝您的幫助!不,我也覺得__with__不會幫助我,但我還在學習,所以我不確定... – Baz