python - 从类中返回 subprocess.Popen 的输出

标签 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) 

最佳答案

这通常是我获取进程输出的方法:

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/

相关文章:

python - 为什么在 Sublime Text 下写入 STD_OUTPUT_HANDLE 会崩溃?

Python 子进程 check_output 比调用慢得多

python - 使用 python-docx 添加页码

Python端口扫描器编辑

python - Keras - 'Node' 对象没有属性 'output_masks'

java : get object name from scanner input

oop - UML设计类图: Class with another class as attribute?

python - 在 OSX 中运行 Tensorflow

java - 为什么忽略接口(interface)隔离原则可能会成为客户端类之间连接的原因?

python - 如何在python子进程中由另一个用户运行文件