python - How to clean up after subprocess.Popen? -
i have long-running python script perl worker subprocess. data sent in , out of child proc through stdin , stdout. periodically, child must restarted.
unfortunately, after while of running, runs out of files ('too many open files'). lsof shows many remaining open pipes.
what's proper way clean after popen'd process? here's i'm doing right now:
def start_helper(self): # spawn perl helper cwd = os.path.dirname(__file__) if not cwd: cwd = '.' self.subp = subprocess.popen(['perl', 'theperlthing.pl'], shell=false, cwd=cwd, stdin=subprocess.pipe, stdout=subprocess.pipe, bufsize=1, env=perl_env) def restart_helper(self): # clean if self.subp.stdin: self.subp.stdin.close() if self.subp.stdout: self.subp.stdout.close() if self.subp.stderr: self.subp.stderr.close() # kill try: self.subp.kill() except oserror: # can't kill dead proc pass self.subp.wait() # ? self.start_helper()
i think that's need:
def restart_helper(self): # kill process if open try: self.subp.kill() except oserror: # can't kill dead proc pass self.start_helper() # wait comes after opened process # if want know how process ended can add # > if self.subp.wait() != 0: # process exits 0 had no errors self.subp.wait()
as far know file objects closed before popen process gets killed.
Comments
Post a Comment