2011-09-28 74 views
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關鍵字嗎?如果是這樣,這個好處是什麼?

謝謝!

回答

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您必須創建的語句,包括必要的縮進。

但也許我已經得到了你的意圖錯誤...

+0

感謝您的幫助!不,我也覺得__with__不會幫助我,但我還在學習,所以我不確定... – Baz

相關問題