Question

I 've written a small python class which extends 'threading.Thread' and sends an automatic e-mail to myself using the SMTP_SSL module. However in my calling python file it seems that things happen more sequencially:

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')

The ouput is:

[DEBUG] (MainThread) Starting the mail thread
[DEBUG] (Worker    ) Mail thread reports that the mail was sent successfully
[DEBUG] (MainThread) This message should be printed before the mail thread exits
[DEBUG] (MainThread) Success

It seems that logging.debug('This message should be printed before the mail thread ends') waits for my other thread to end and only then prints its message. Why is this happening and how should I go about it?

EDIT: Well it seems that if I replace

returnValue = myMailInstance.run()

with:

returnValue = myMailInstance.start()

works OK however it now prints nothing on returnValue...

Was it helpful?

Solution

You need a couple of things to get your code working as you expect.

First: Add to your thread instance an attribute result and some access method.

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.

Second: You main thread has to wait for myMailInstance ends, and then ask for the result. So, you need to call join on your thread.

myMailInstance.start()

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

myMailInstance.join()

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

That's all.

OTHER TIPS

As bakuriu wrote, start() is the correct way to run thread. But It doesn't return value, because it is unknown, the thread can run for a while to get a result. So you should get the return value using other way. i.e. this should be helpful for you:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top