我正在尝试实现一个多线程类,并希望使用输出来确定程序中下一步要做什么。如何将 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)
最佳答案
这通常是我获取进程输出的方法:
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)
希望我的例子对你有帮助。问候。
关于python - 从类中返回 subprocess.Popen 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47147857/