2017-09-29 12 views
0

ファイルのセットに対してさまざまなツールを実行するには、次のCommandクラスを使用して呼び出します。pythonサブプロセスが終了していません

import subprocess 
import threading 
import logging 
logger = logging.getLogger('root') 


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

    def run(self, timeout, logfile): 
     def target(): 
      logger.info('Thread started') 
      logger.info('Command: %s' % self.cmd) 
      if logfile is None: 
       self.process = subprocess.Popen(self.cmd, shell=True) 
      else: 
       logger.info('logging to file %s' % logfile.name) 
       self.process = subprocess.Popen(self.cmd, shell=True, stdout=logfile) 
      self.process.communicate() 
      logger.info('Thread finished') 
      self.process.kill() 
     thread = threading.Thread(target=target) 
     # make it a daemon 
     thread.daemon = True 
     thread.start() 
     thread.join(timeout) 
     if thread.is_alive(): 
      logger.warn('Terminating process') 
      thread.join() 
      self.process.kill() 
     logger.info('Thread Returncode: %d' % self.process.returncode) 
     return self.process.returncode 

私が直面している問題は、次のとおりです。

  • 私は実行ツール/コマンドは、Pythonプログラムが実行される場合は特に長く、正常に終了しないこと(3+時間)。

答えて

0

問題はあなたがシェルでプロセスを開いているということです=ここで真

self.process = subprocess.Popen(self.cmd, shell=True, stdout=logfile) 

ソリューション:How to terminate a python subprocess launched with shell=True

+0

だから私は(self.process.killを交換する)あなたのリンクから溶液で私は推測する。 – Derping

関連する問題