我在以下部分中包含脚本的这一部分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
即proc
方法中的返回值inp
,但是当前代码无法实现此目的,方法之间的通信不起作用。
问题的直接原因是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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句