Return 使用线程守护程序从构造函数的方法到另一个方法的变量值

Return a variable's value from a method of the constructor to another method using a thread daemon

我在 python 中有这部分脚本:

class Filtro:
    def __init__(self,cmd):
       def exec_cmd():
            proc = subprocess.Popen([cmd, '-'],
                            stdin=subprocess.PIPE,
                        )
            return proc

       self.thr=threading.Thread(name="Demone_cmd",target=exec_cmd)
       self.thr.setDaemon(True)
       self.proc=self.thr.start()

    def inp(self,txt):
       f=open(txt,"r")
       self.proc.communicate(f.read())
       f.close()


filtro=Filtro(sys.argv[1])
filtro.inp(sys.argv[2])

我想要 exec_cmd 的 return 值——即 proc——在方法 inp 中,但当前代码没有实现这一点—— - 方法之间的通信不起作用。

您的问题的直接原因在self.proc = self.thr.start()start() 方法启动了一个线程并且没有return 值。因此 self.proc 设置为 None 并且 self.proc.communicate(f.read()) 将导致异常。

更一般地说,在您的代码段中使用线程似乎有点矫枉过正,subprocess.Popen() 本身已经启动了一个与您的脚本并行运行的进程,您可以使用它的 communicate() 方法来将数据发送到流程并检索流程结果 (docs)。

使用 communicate() 的一个重要细节是使用用于 stdout 和 stderr 的管道启动进程,否则您将无法返回进程结果。因此,如果您将构造函数替换为以下内容,您应该能够在 inp() 方法中看到处理结果:

def __init__(self,cmd):
    self.proc = subprocess.Popen([cmd, '-'], 
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE, 
                                stderr=subprocess.PIPE)