2016-07-28 58 views
0

我是OOP的新手,正試圖弄清楚如何獲得類之外的結果,以便決定下一步在我的程序中做什麼。使用Python返回類或函數以外的字符串

我解壓縮一個文件,如果它需要太長時間,我希望進程終止。此代碼將做到這一點:

class Command(object): 
    def __init__(self,cmd): 
     self.cmd = cmd 
     self.process = None 

    def run(self,timeout): 
     def target(): 
      print("Thread started") 
      self.process = subprocess.Popen(self.cmd) 
      self.process.communicate() 
      print("Thread finished") 

     thread = threading.Thread(target=target) 
     thread.start() 

     thread.join(timeout) 
     if thread.is_alive(): 
      print("\nTerminating process") 
      self.process.terminate() 
      thread.join()    
     print(self.process.returncode) 

def unzip_file(file,dirout,attempt): 
    just_name = os.path.splitext(file)[0]  
    print('unzip started at {} for {}'.format(datetime.datetime.now(),file)) 
    command = Command(zip_exe+' x '+file+' -o'+path+dirout) 
    command.run(timeout = 300) 

......但是如果我想獲得命令輸出,在類內部調用的函數之外呢?對一個名爲'tmp'的變量說。我已經添加了兩條註釋行來說明我正在嘗試做什麼,當然這會返回一個錯誤。

class Command(object): 
    def __init__(self,cmd): 
     self.cmd = cmd 
     self.process = None 

    def run(self,timeout): 
     def target(): 
      print("Thread started") 
      self.process = subprocess.Popen(self.cmd) 
      self.tmp = self.proc.stdout.read() #get the command line output 
      self.process.communicate() 
      print("Thread finished") 

     thread = threading.Thread(target=target) 
     thread.start() 

     thread.join(timeout) 
     if thread.is_alive(): 
      print("\nTerminating process") 
      self.process.terminate() 
      thread.join()    
     print(self.process.returncode) 

def unzip_file(file,dirout,attempt): 
    just_name = os.path.splitext(file)[0]  
    print('unzip started at {} for {}'.format(datetime.datetime.now(),file)) 
    command = Command(zip_exe+' x '+file+' -o'+path+dirout) 
    command.run(timeout = 300) 
    print(self.tmp) #print the command line output (doesn't work) 
+0

你爲什麼不在'target'內部打印(self.tmp)? – DeepSpace

+0

因爲我想在我的程序的其他地方使用字符串。 – sparrow

回答

1

此行self.tmp = self.proc.stdout.read()將一些數據放入成員變量中。然後,您可以通過簡單的使用參照對象使用它的類之外:

... 
command.run(timeout = 300) 
print(command.tmp) 
1

您的問題似乎是,該標識符self在功能unzip_file沒有定義。試着用

print(command.tmp) 

標識符self更換

print(self.tmp) #print the command line output (doesn't work) 

在類的範圍內使用,並指類的實例時具有特殊的意義。在別處使用時(如unzip_file),標識符沒有特殊含義,只是一個未定義的標識符。

除了您的實際問題,您可能還想研究線程之間的通信機制。 Queue module是一個很好的地方,如果你已經瞭解基礎知識。如果你是新手,那麼this one是一個體面的介紹。

+0

感謝您提供有用資源的鏈接。 – sparrow