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()
代码能够在第一次尝试时成功运行并记录所有设备的结果,但在第二次尝试时,它在代码中某个地方卡住了,显示“猴子命令:唤醒”。
线程出了什么问题,导致它这样运行呢?
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()