How to wait for an input without blocking timer in python?

£可爱£侵袭症+ 提交于 2019-12-10 10:58:49

问题


I need to print a message every x seconds, at the same time, I need to listen to the user's input. If 'q' is pressed, it should kill the program.

For example

some message
.
. # after specified interval
. 
some message
q # program should end

The current problem I face now is that raw_input is blocking which stops the my function from repeating the message. How do I get input reading and my function to run in parallel?

EDIT: It turns out that raw_input was not blocking. I misunderstood how multi-threading works. I'll leave this here in case any one stumbles upon it.


回答1:


You can use threading to print your message in a different thread.

import threading

t = threading.Timer(30,func,args=[])
t.start()

Where 30 is how often to call func.

func is the function to call in a different thread.

And args is an array of the arguments to call the function with

If you want just one call to a different function you can do

t = threading. Thread(target=func, args=[]) 
t.start() 

This will make func run in parallel




回答2:


import threading
import time as t

value = 0

def takeInput():
    """This function will be executed via thread"""
    global value
    while True:
        value = raw_input("Enter value: ")
        if value == 'q':
            exit()  # kills thread
        print value
    return

if __name__ == '__main__':
    x = int(raw_input('time interval: '))
    thread = threading.Thread(target=takeInput)
    thread.start()
    while True:
        if value == 'q':
            exit()  # kills program
        print 'some message'
        t.sleep(x)


来源:https://stackoverflow.com/questions/32369495/how-to-wait-for-an-input-without-blocking-timer-in-python

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