44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
import subprocess
|
|
import os
|
|
import tempfile
|
|
class SubprocessWraper(object):
|
|
|
|
def __init__(self, python, workdir, args, activate_env) -> None:
|
|
super().__init__()
|
|
self.returncode = None
|
|
self.python = python
|
|
self.workdir = workdir
|
|
self.args = args
|
|
self.p = None
|
|
self.activate_env = activate_env
|
|
|
|
def run(self, verbose = True):
|
|
# print(' && '.join([self.activate_env, ' '.join([self.python, *self.args])]))
|
|
try:
|
|
|
|
self.p = subprocess.Popen(' && '.join([self.activate_env, ' '.join([self.python, *self.args]) ]), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.workdir)
|
|
self.returncode = self.p.poll()
|
|
while self.returncode is None:
|
|
line = self.p.stdout.readline()
|
|
self.returncode = self.p.poll()
|
|
line = line.strip()
|
|
if verbose:
|
|
try:
|
|
line = line.decode('utf-8')
|
|
except:
|
|
try:
|
|
line = line.decode('gbk')
|
|
except:
|
|
line = str(line)
|
|
yield line
|
|
except Exception as e:
|
|
yield str(e)
|
|
|
|
finally:
|
|
self.kill()
|
|
|
|
def kill(self):
|
|
try:
|
|
self.p.kill()
|
|
except:
|
|
pass |