Is it possible to kill the parent thread from within a child thread in python?

后端 未结 2 1537
离开以前
离开以前 2021-02-20 18:50

I am using Python 3.5.2 on windows.

I would like to run a python script but guarantee that it will not take more than N seconds. If it does ta

2条回答
  •  走了就别回头了
    2021-02-20 19:24

    You can use _thread.interrupt_main (this module is called thread in Python 2.7):

    import time, threading, _thread
    
    def long_running():
        while True:
            print('Hello')
    
    def stopper(sec):
        time.sleep(sec)
        print('Exiting...')
        _thread.interrupt_main()
    
    threading.Thread(target = stopper, args = (2, )).start()
    
    long_running()
    

提交回复
热议问题