我是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)
你爲什麼不在'target'內部打印(self.tmp)? – DeepSpace
因爲我想在我的程序的其他地方使用字符串。 – sparrow