How to use threading to get user input realtime while main still running in python

后端 未结 1 645
长发绾君心
长发绾君心 2020-12-14 13:55

In the WHILE loop, I wanna run two function, one is base function, which will run everytime, the other is user_input function, when user input \'disarm\', program can run us

相关标签:
1条回答
  • 2020-12-14 14:21

    You really need to be more specific. Why do these need to be in threads? You should show us what you have tried, or describe in more detail what you are trying to accomplish.

    In your current setup, you are putting the thread inside a loop, so it can't run independently of each user input.

    edited: here is some cleaned up code as an example for you, based on your post edits and comments.

    import threading
    import time
    import sys
    
    def background():
            while True:
                time.sleep(3)
                print 'disarm me by typing disarm'
    
    
    def other_function():
        print 'You disarmed me! Dying now.'
    
    # now threading1 runs regardless of user input
    threading1 = threading.Thread(target=background)
    threading1.daemon = True
    threading1.start()
    
    while True:
        if raw_input() == 'disarm':
            other_function()
            sys.exit()
        else:
            print 'not disarmed'
    
    0 讨论(0)
提交回复
热议问题