python 播放音乐 不中断_python – 在不中断程序的情况下休眠

我正在创建一个在一段时间后倒计时的程序,并要求输入秒数以添加到倒计时. (不是真的,只是一个例子).

有点像这样:

mytime = 10

while True:

print(time)

mytime -= 1

time.sleep(1)

mytime += int(input('add > '))

有两个问题.

>我希望时间在一秒钟之后仍然可以打勾,但不想在输入之前等待第二秒.与this类似.我想我需要使用线程.

>我也不想等待输入!我只想让它在不等待输入的情况下打勾,当我想要时我可以输入东西.

谢谢你的帮助.

解决方法:

有一种比从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被读取.

标签:python,multithreading,python-3-x

来源: https://codeday.me/bug/20191008/1872030.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值