从类中返回subprocess.Popen的输出

时间:2017-11-07 00:02:50

标签: python oop subprocess

我试图为多线程实现一个类,并希望使用输出来确定我的程序中的下一步操作。如何将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) 

2 个答案:

答案 0 :(得分: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)

我希望我的榜样可以帮到你。问候。

答案 1 :(得分:0)

我显然需要加快OOP的速度。无论如何这是我用过的答案......

#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来访问结果:command.tmp。