将参数从类传递到继承自threading.Thread的另一个类

时间:2015-05-12 16:52:33

标签: python multithreading

我的python代码中有两个类。类Filtro必须向类Man_Thr发送两个参数,但如果我通过结构函数发送它们,我永远不会调用线程metod start的结构函数。这是我的代码:

import threading

class Man_Thr(threading.Thread):
  def __init__(self,cmd,q):
    self.comando=cmd
    self.coda=q

  def run(self):
    try:
        proc=subprocess.Popen([self.comando],
                shell=True,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
        self.coda.put(proc)
    except:
        print "Il comando", self.comando, "non esiste. Riprovare."
        self.coda.put(-1)

class Filtro(Man_Thr):
  def __init__(self,cmd):
    q=Queue.Queue()
    thr=Man_Thr(cmd,q)
    thr.start()
    self.result=q.get()

filtro=Filtro(' '.join(sys.argv[1:len(sys.argv)-1]))

这是我的输出:

Traceback (most recent call last):
File "filtro2.py", line 75, in <module>
  filtro=Filtro(' '.join(sys.argv[1:len(sys.argv)-1]))
File "filtro2.py", line 45, in __init__
  thr.start()
File "/usr/lib64/python2.6/threading.py", line 465, in start
  raise RuntimeError("thread.__init__() not called")
RuntimeError: thread.__init__() not called

我以这种方式运行脚本:

 python filtro2.py ./a.out input.txt

将参数从派生类发送到基类的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您需要致电threading.Thread&#39; __init__。通常我们会使用super

class Parent(object):
    def __init__(self, *args, **kwargs):
        print("You've called Parent.__init__")

class Child(Parent):
    def __init__(self, child_arg, *args, **kwargs):
        print("You've called Child.__init__ with child_arg={}".format(child_arg))
        super().__init__(*args, **kwargs)

在你的情况下,你想做:

class Man_Thr(threading.Thread):
    def __init__(self, cmd, q, *args, **kwargs):
        self.comando = cmd
        self.coda = q
        super().__init__(*args, **kwargs)
    ...  # the rest of your class as-is

class Filtro():  # why are you inheriting? This isn't a child...
    def __init__(self, cmd, *args, **kwargs):
        q = queue.Queue()
        thr = Man_Thr(cmd, q, *args, **kwargs)
        thr.start()
        self.result = q.get()

filtro = Filtro(' '.join(sys.argv[1:-1])

一般模式是让每个类接受某些参数,并将任何其他参数传递给其父级&#39; __init__方法。

我还敦促你使用某种参数解析模块,而不是试图自己处理它。根据您的Python版本,argparse位于3.2 +的stdlib中。

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('outfile', type=argparse.FileType('w'))
parser.add_argument('infile', type=argparse.FileType('r'))

args = parser.parse_args()

for line in args.infile:
    print(line.strip())
args.infile.seek(0)
for line in args.infile:
    args.outfile.write(line)