如何在不阻塞python中的计时器的情况下等待输入? [英] How to wait for an input without blocking timer in python?

查看:415
本文介绍了如何在不阻塞python中的计时器的情况下等待输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要每x秒打印一条消息,同时,我需要听用户的输入.如果按下"q",它将杀死程序.

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.

例如

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

我现在面临的当前问题是raw_input正在阻止,这阻止了我的功能重复该消息.如何获取输入读数和要并行运行的功能?

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?

事实证明raw_input没有被阻止.我误解了多线程的工作原理.如果有人偶然发现,我将其留在这里.

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.

推荐答案

您可以使用线程在其他线程中打印消息.

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

import threading

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

调用func的频率为30.

Where 30 is how often to call func.

func是在另一个线程中调用的函数.

func is the function to call in a different thread.

并且args是使用以下参数调用函数的参数数组:

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() 

这将使func并行运行

This will make func run in parallel

这篇关于如何在不阻塞python中的计时器的情况下等待输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆