run a python program on a new thread -
i have 2 programs program1.py commandline interface takes command user program2.py has programme runs relevant programme per command.
program 1 has has quit_program() module in our simple universe.. lets have 1 command , 1 programme lets say...
program1.py
def main(): while true: try: command = raw_input('> ') if command == "quit" : homecoming if command == '': go on except keyboardinterrupt: exit() parsecommand(command)
and have:
if commmand == "hi": say_hi()
now program2 has
def say_hi(): #do something..
now there can 2 cases... either say_hi() completes in case no issue... want if user enters command (say: end) say_hi() terminated in between..
but current implementation sequential.. mean dont type on terminal untill execution completed.. somethng tells me say_hi() should running on thread?
i not able think straight this. suggestions? thanks
the threading module looking for.
import threading t = threading.thread(target=target_function,name=name,args=(args)) t.daemon = true t.start()
the .daemon
alternative makes don't have explicitly kill threads when app exits... threads can quite nasty otherwise
specific question , question in comments, say_hi
function can called in thread such:
import threading if commmand == "hi": t = threading.thread(target=say_hi, name='saying hi') #< note did not phone call function, instead sent parameter t.daemon = true t.start() #< starts thread execution in background
as side note, must create sure using thread safe functions within of threads. in illustration of saying hi, want utilize logging module instead of print()
import logging logging.info('i saying hi in thread-safe manner')
you can read more in python docs.
python
No comments:
Post a Comment