我创建了一个线程类,然后调用它们的start和join,但是当我运行Thread.isAlive()所有这些时,返回为False。我不确定我是否正确设置了线程类,我试着按照这篇文章How to use threading in Python? Michael Safyan的回答。
这是我的Thread类
class Thread(threading.Thread):
def __init__(self, host, communityString, deviceID, script):
super(Thread, self).__init__()
self.host = host
self.communityString=communityString
self.deviceID = deviceID
self.script=script
def CreateScript(self):
#ScriptsToGenerate = GetDatasourceScripts(deviceID)
print self.script['scriptType']
#We check if script type is SNMP and if it is we will add the oids that matter into the SNMP script
if self.script['scriptType'] == "SNMP":
print self.script['parentOID']
#walk the parent node to see if these exist
oidsToInputInScript = SNMPWalkChildren(self.host, self.communityString, self.script['OID'])
print oidsToInputInScript
if oidsToInputInScript != "":
self.script['script'].replace("[oid]", oidsToInputInScript)
SaveScript(self.host, self.script['timeInterval'], self.script)
def SaveScript(name, Interval, script):
createFolder = ""
for root, dirs, files in os.walk("/home/pi/", topdown=False):
for name in dirs:
if name == "myDir":
createFolder = os.path.join(root, name)
print createFolder
absPath = createFolder + "/" + Interval
print absPath
if not os.path.exists(absPath):
os.system("sudo mkdir " + absPath)
os.chmod(absPath, stat.S_IRWXO | stat.S_IRWXU | stat.S_IRWXG)
scriptName = name.replace(".", "")
#create script file and save it in that location
#need to replace "name" with a distinguishable name
saveFile = absPath + "/" + scriptName + "_" + script["dsID"] + "_" + script["dpID"] + ".py"
print saveFile
with open(saveFile, "w") as script_file:
os.chmod(saveFile, stat.S_IRWXO | stat.S_IRWXU | stat.S_IRWXG)
script_file.write(script["text"])
def SNMPWalkChildren(host, communityString, OID):
result = ""
try:
cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
cmdgen.CommunityData(communityString),
cmdgen.UdpTransportTarget((host, 161)),
parentOID
)
if errorIndication:
print(errorIndication)
else:
if errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
)
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
result += "\"" + str(name) + "\"" + ', '
return result[:-2]
finally:
return result
这里是我在线程上调用start的地方
threadList = list()
#Loop through and create threads for each script
for scripts in ds:
thread = Thread(name, communityString, deviceID, scripts)
threadList.append(thread)
print "Thread has started"
print scripts
thread.start()
thread.join()
for threads in threadList:
print(threads.isAlive())
答案 0 :(得分:3)
您在每个线程启动时加入;这意味着它必须在循环继续之前完成。所以当你进入第二个for循环时,所有线程都已完成,因此它们都没有活着。