使用线程守护进程将一个变量的值从构造函数的方法返回到另一个方法

2024-04-25 17:58:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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])

我想要方法inp中的exec_cmd的返回值,即proc,但是当前的代码没有实现这一点——方法之间的通信不起作用。你知道吗


Tags: 方法selftxt脚本cmddefsysproc
1条回答
网友
1楼 · 发布于 2024-04-25 17:58:39

问题的直接原因是self.proc = self.thr.start()start()方法启动一个线程,并且没有返回值。因此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)

相关问题 更多 >