Non-Blocking raw_input() in python

后端 未结 4 1988
感情败类
感情败类 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条回答
  • 2020-12-11 05:52

    You created a thread but forget to start it:

    listener = threading.Thread(target=kbdListener)
    listener.start()
    
    0 讨论(0)
  • 2020-12-11 05:58

    I found the accepted answer didn't work for me - it would still block at raw_input even in a separate thread. However, when I switched the threads around it worked right away.

    import threading 
    
    def mainWork():
      while 1:
        #whatever you wanted to do until an input is received
    
    myThread = threading.Thread(target=mainWork)
    myThread.start()
    
    while 1:
      input = raw_input()
      #do stuff with input when it is received
    
    0 讨论(0)
  • 2020-12-11 05:59

    In addition to MydKnight's answer (starting the thread), you need to change rawInput to raw_input, and it needs to be in some sort of while loop otherwise you'll only get one raw_input() logged.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题