python中的线程不工作

2024-10-03 17:28:59 发布

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

我需要做的是对多个设备反复运行同一组命令。但我需要同时做。向其他设备发送命令集之前,间隔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()

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

使它表现出这种行为的线程有什么问题?在


Tags: path代码inselfforinitosline
1条回答
网友
1楼 · 发布于 2024-10-03 17:28:59

线程代码必须在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()

相关问题 更多 >