如何在Python中使用线程正确执行非阻塞任务

2024-09-30 06:19:14 发布

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

我写了一个小python类,它扩展了线程。线程'并使用SMTP_SSL模块自动向我发送电子邮件。然而,在我调用的python文件中,事情似乎发生得更为循序渐进:

import sysErrorMail
import logging

logging.basicConfig(level=logging.DEBUG,
                format='[%(levelname)s] (%(threadName)-10s) %(message)s',
                )

returnValue = -1
myMailInstance = sysErrorMail.sysMail()
logging.debug('Starting the mail thread')

returnValue = myMailInstance.run()

logging.debug('This message should be printed before the mail thread ends')

if returnValue == 0:
    logging.debug('Success')
elif returnValue == 1:
    logging.debug('Failed')

输出是:

^{pr2}$

似乎logging.debug('This message should be printed before the mail thread ends')等待另一个线程结束,然后才打印其消息。为什么会这样?我该怎么做?在

编辑:看来如果我换了

returnValue = myMailInstance.run()

有:

returnValue = myMailInstance.start()

工作正常,但它现在不打印返回值。。。在


Tags: therundebugimportmessageloggingmailbe
2条回答

正如bakuriu所写,start()是运行线程的正确方法。但是它不返回值,因为它是未知的,线程可以运行一段时间来获得结果。所以你应该用其他方法得到返回值。i、 e.这对你有帮助:

how to get the return value from a thread in python?

你需要一些东西来让你的代码像你期望的那样工作。在

首先:向线程实例添加属性result和一些访问方法。

import threading
class YourThread(threading.Thread):
    ...                # code you already have.
    self.__result      # code I'm suggesting.

    def get_result(self):
        return self.__result

    def run(self):
        # You have to modify the code in your run method in order to provide
        # a value for self.__result.

第二:主线程必须waitmyMailInstance结束,然后请求结果。所以,你需要在你的线程上调用join

^{pr2}$

仅此而已。在

相关问题 更多 >

    热门问题