Python 线程未启动

标签 python multithreading

我已经创建了一个线程类,并对它们调用 start 和 join ,但是当我运行 Thread.isAlive() 时,所有这些类都返回 False。我不确定我是否正确设置了线程类,我尝试按照这篇文章 How to use threading in Python? 进行操作迈克尔·萨菲安的回答。

这是我的 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())

最佳答案

您在每个线程启动时加入它;这意味着它必须在循环继续之前完成。因此,当您到达第二个 for 循环时,所有线程都已完成,因此没有一个线程仍处于事件状态。

关于Python 线程未启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31943018/

相关文章:

python - 查找并打印列表中元素的索引(字符串)

python - 如何使用 LibVLC 更改 MediaListPlayer 中的播放音量?

python - ImportError at/login 没有名为登录的模块

c - 主线程和其他线程有什么区别?

python - 如何从删除的文件中删除 PyDev 调试器断点?

python - 错误 : (gcloud. preview.app.deploy) 错误响应 : [400] Invalid character in filename: flask/ext/setuptools/script (dev). tmpl

java - 为什么 java ExecutorService newSingleThreadExecutor 产生两个线程?

multithreading - 如何在多线程环境下修改Kotlin StateFlow内容?

c# - 游戏编程及定时器数量

c# - 线程终止时调用方法