python运行时不让电脑休眠_python – 在不中断程序的情况下休眠

有一种比从0开始自己的线程更简单的方法.为您准备的Timer线程:

import threading

timer = None

def wuf ():

global timer

print "Wuf-wuf!"

timer = threading.Timer(5, wuf)

timer.start()

timer = threading.Timer(5, wuf)

timer.start()

input() # Don't exit the program

此代码将等待5秒钟,然后开始打印“Wuf-wuf!”每5秒钟.

如果你想从主线程中停止它:

timer.cancel()

但是如果您使用事件驱动的GUI系统(如wxPython或PyQT)编写GUI应用程序,那么您应该使用他们的事件管理计时器.特别是如果您要从计时器回调更改某些GUI状态.

编辑:

哦,好的,这是你的完整答案:

import threading

seconds = 1 # Initial time must be the time+1 (now 0+1)

timer = None

def tick ():

global seconds, timer

seconds -= 1

if seconds==0:

print("%i seconds left" % seconds)

print("Timer expired!")

return

# printing here will mess up your stdout in conjunction with input()

print("%i second(s) left" % seconds)

timer = threading.Timer(1, tick)

timer.start()

seconds += int(input("Initial countdown interval: "))

tick()

while 1:

seconds += int(input("Add: "))

if not timer.is_alive():

print("Restarting the timer!")

seconds += 1

tick()

或者带有线程的简单版本(但是有点clumsyer然后使用threading.Thread):

from thread import start_new_thread as thread

from time import sleep

seconds = 1 # Initial time+1

alive = 0

def _tick ():

global seconds, alive

try:

alive = 1

while 1:

seconds -= 1

if seconds==0:

print("%i seconds left" % seconds)

print("Timer expired!")

alive = 0

return

# printing here will mess up your stdout in conjunction with input()

print("%i second(s) left" % seconds)

sleep(1)

except: alive = 0

def tick ():

thread(_tick,())

# Then same as above:

seconds += int(input("Initial countdown interval: "))

tick()

while 1:

seconds += int(input("Add: "))

if not alive:

print("Restarting the timer!")

seconds += 1

tick()

您必须意识到在线程中使用stdout将在输入()输出的提示消息之后插入打印的文本.

这将令人困惑.如果你想避免这种情况,那么你将不得不编写另一个线程来获取队列中的消息并输出它们.

如果最后一条消息是提示消息,则必须将其从屏幕中删除,写入新消息,然后返回提示消息,并相应地定位光标.

你可以通过在threading.Thread的子类中实现类似文件的接口,然后用它替换sys.stdout来实现.也许重写input()以指示何时提示消息输出并且stdin被读取.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值