run a python program on a new thread

后端 未结 1 1925
独厮守ぢ
独厮守ぢ 2021-01-07 04:59

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.<

相关标签:
1条回答
  • 2021-01-07 05:53

    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.

    0 讨论(0)
提交回复
热议问题