0

我需要做的是一次又一次地对多个设备运行同一组命令。但我需要同时进行。将命令集发送到其他设备之前的 1-3 秒间隔是可以的。所以我想到了使用线程。

这是代码的运行方式。

class UseThread(threading.Thread):

    def __init__(self, devID):
        super(UseThread, self).__init__()
        ... other commands ....
        ... other commands ....
        ... other commands ....

   file = open(os.path.dirname(os.path.realpath(__file__)) + '\Samples.txt','r')

   while 1:
       line = file.readline()
       if not line:
           print 'Done!'
           break
       for Code in cp.options('code'):
           line = cp.get('product',Code)
           line = line.split(',')
           for devID in line:
               t=UseThread(devID)
               t.start()

它能够在所有设备上运行并记录第一次试验的结果,但对于第二次试验,它挂在代码中的某个地方,上面写着“猴子命令:唤醒”

使它以这种方式运行的线程有什么问题?

4

1 回答 1

1

线程代码必须在run()方法中。

方法中的任何内容都__init__()将在设置线程之前被调用,当创建新对象时(因此它是调用线程的一部分)。

class UseThread(threading.Thread):
    def __init__(self, devID):
        super(UseThread, self).__init__()
        self.devID = devID
    def run(self):
        ## threaded stuff ....
        ## threaded stuff ....
        pass

## ...
for devID in line:
   t=UseThread(devID) # this calls UseThread.__init__()
   t.start()          # this creates a new thread that will run UseThread.run()
于 2013-02-12T09:24:17.687 回答