Non-Blocking raw_input() in python

后端 未结 4 1995
感情败类
感情败类 2020-12-11 05:11

After digging around in SO for a while, I still haven\'t found a good answer to what I would hope is a fairly common need. Basically I need a main thread to do \"stuff\" unt

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 06:01

    If you actually want to keep the while loop going on forever, you will need to create a new thread and start it, each time the old one has finished.

    I updated the example in the question to make that work:

    import threading
    import time
    
    kbdInput = ''
    playingID = ''
    finished = True
    
    def kbdListener():
        global kbdInput, finished
        kbdInput = raw_input("> ")
        print "maybe updating...the kbdInput variable is: {}".format(kbdInput)
        finished = True
    
    while True:
        print "kbdInput: {}".format(kbdInput)
        print "playingID: {}".format(playingID)
        if playingID != kbdInput:
            print "Received new keyboard Input. Setting playing ID to keyboard input value"
            playingID = kbdInput
        else:
            print "No input from keyboard detected. Sleeping 2 seconds"
        if finished:
            finished = False
            listener = threading.Thread(target=kbdListener)
            listener.start()
        time.sleep(2)
    

提交回复
热议问题