frazman
frazman

Reputation: 33243

run a python program on a new thread

I have two programs program1.py is like commandline interface which takes command from user program2.py has the program which runs the relevant program as per the command.

Program 1 has also has an quit_program() module In our simple universe.. lets say I have just one command and just one program So lets say...

program1.py

def main():
   while True:
        try:

            command = raw_input('> ')
            if command == "quit" :
                return

            if command == '':
                continue
        except KeyboardInterrupt:
            exit()

        parseCommand(command)

And then I have:

 if commmand == "hi":
       say_hi()

Now program2 has

   def say_hi():
      #do something..

Now there can be two cases... Either say_hi() completes in which case no issue... But what i want is that if user enters a command (say: end) then this say_hi() is terminated in between..

But my current implementation is very sequential.. I mean I dont get to type anything on my terminal untill the execution is completed.. Somethng tells me that the say_hi() should be running on another thread?

I am not able to think straight about this. Any suggestions? Thanks

Upvotes: 3

Views: 21992

Answers (1)

Dave Lasley
Dave Lasley

Reputation: 6252

The threading module is what you are looking for.

import threading
t = threading.Thread(target=target_function,name=name,args=(args))
t.daemon = True
t.start()

The .daemon option makes it so you don't have to explicitly kill threads when your app exits... Threads can be quite nasty otherwise

Specific to this question and the question in the comments, the say_hi function can be called in another thread as such:

import threading
if commmand == "hi":
   t = threading.Thread(target=say_hi, name='Saying hi') #< Note that I did not actually call the function, but instead sent it as a parameter
   t.daemon = True
   t.start() #< This actually starts the thread execution in the background

As a side note, you must make sure you are using thread safe functions inside of threads. In the example of saying hi, you would want to use the logging module instead of print()

import logging
logging.info('I am saying hi in a thread-safe manner')

You can read more in the Python Docs.

Upvotes: 16

Related Questions