0

您好我正在尝试使用下面的代码从字典条目中启动一个线程。脚本中的其余代码已知良好且功能齐全。我必须能够从一堆不同的子例程中进行选择,所以我想从代码中删除尽可能多的样板。谢谢各位大侠!!!!

class worker_manager:

     i = test_imports()
     template('one': i.import_1, 'two': i.import_2);

     def __init__(self):
        self.children = {}

     def generate(self, control_Queue, threadName, runNum):
         p = multiprocessing.Process(target=self.template[threadName], args=(control_Queue, runNum))
         self.children[threadName] = p  
         p.start()    


      def terminate(self, threadName):
          self.children[threadName].join

当我运行此代码时,我收到此错误:

  File "dynamicTest1.py", line 53
    template('one': i.import_1, 'two': i.import_2);
              ^
   SyntaxError: invalid syntax

有人有什么建议吗?

编辑:这是正常线程的工作方式:

def generate(self, control_Queue, threadName, runNum):
        i = test_imports()
        if threadName == 'one':
            print ("Starting import_1 number %d") % runNum
            p = multiprocessing.Process(target=i.import_1, args=(control_Queue, runNum))
            self.children[threadName] = p
            p.start()  

我想用p = multiprocessing.Process(target=i.import_1, args=(control_Queue, runNum))字典替换目标,以消除对大量 if/elif/else 语句的需求。

4

2 回答 2

1

您确实有语法错误。您的模板声明应如下所示:

template = {'one': i.import_1, 'two': i.import_2};

或者你可以这样做:

template = dict(one=i.import_1, two=i.import_2);

请参阅:http ://docs.python.org/2/tutorial/datastructures.html#dictionaries

于 2013-09-15T03:15:51.070 回答
0

处理这个问题的正确方法是:

class worker_manager:

     i = test_imports()
     template = {'one': i.import_1, 'two': i.import_2}

 def __init__(self):
        self.children = {}

     def generate(self, control_Queue, threadName, runNum):
         p = multiprocessing.Process(target=self.template[threadName], args=(control_Queue, runNum))
         self.children[threadName] = p  
         p.start()    


     def terminate(self, threadName):
         self.children[threadName].join

这只是代码执行广告的语法问题

于 2013-09-15T01:53:47.983 回答