2017-11-07 13 views
1

私はマルチスレッドのためのクラスを実装しようとしており、出力を使って自分のプログラムで次に何をするかを決定したいと思っています。 self.processの出力を文字列として返すにはどうすればよいですか? self.process.communicateの出力を返そうとすると、エラーが発生します。サブプロセスの出力をクラス内から返す

#class for multi threading 
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,stdout=subprocess.PIPE) 
      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(zipped):  
    command = Command(zip_exe+' x '+zipped) 
    command.run(timeout = 12000) 

unzip_file(zipped) 
+0

subprocess.communicate()はタプル(stdoutdata、stderrdata)を返します。それがプロセスの出力です。 –

+0

「unzip_file」を実行した後、どうすればアクセスできますか? – sparrow

答えて

1

これは私が私のプロセスの出力を得るために何をすべきか、通常は次のとおりです。

class SExec: 

def __init__(self, _command): 

    _process = Popen(_command, shell=True, stdout=PIPE, stderr=STDOUT, close_fds=True) 

    if _process.stderr is None: 
     self.stdout = (_process.stdout.read()).decode("utf-8") 
     self.return_code = _process.returncode 
    else: 
     self.stdout = None 
     self.stderr = _process.stderr.decode("utf-8") 

その後、私が欲しいとき、一例として、何かを実行し、それのリターンを得るために、私が行うことができます。

dir_info = SExec('ls -lA').stdout 
    for _line in dir_info.split('\n'): 
     print(_line) 

私の例があなたに役立つことを望みます。よろしく。

0

私は明らかにOOPでスピードアップする必要があります。 command.tmp:とにかく、ここで私が使用し...

#class for multi threading 
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,stdout=subprocess.PIPE) 
      self.tmp = self.process.stdout.read() 
      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) 

をその後の結果は、インスタンス名を使用した後self.tmpにアクセスすることによりアクセスすることができる答えがあります。

関連する問題