waiting for user input in separate thread

纵然是瞬间 提交于 2019-12-01 06:21:56

Looks like there is no way to time user input. In the link that SmartElectron provided, the solution does not work since the timer is halted once the raw_input is requested.

Best solution so far is:

# Declare a mutable object so that it can be pass via reference
user_input = [None]

# spawn a new thread to wait for input 
def get_user_input(user_input_ref):
    user_input_ref[0] = raw_input("Give me some Information: ")

mythread = threading.Thread(target=get_user_input, args=(user_input,))
mythread.daemon = True
mythread.start()

for increment in range(1, 10):
    time.sleep(1)
    if user_input[0] is not None:
        break
SmartElectron

in your case don't worry for close the thread abruptly. In link, say

It is generally a bad pattern to kill a thread abruptly, in python and in any language. Think of the following cases:

  • the thread is holding a critical resource that must be closed properly.
  • the thread has created several other threads that must be killed as well.

Close database connection, files opened, etc. resources that need be closed properly, in this cases close the thread properly is fundamental. In this case your solution is valid.*

If this solution does not satisfy you can use How to set time limit on input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!