简体   繁体   English

(python)使用threading.Timer调用时的行为不同

[英](python) Different behaviour when called using threading.Timer

I want to make a little command line music player based on the python module "mp3play". 我想基于python模块“ mp3play”制作一个命令行音乐播放器。 I want to check regularly, if a song has stopped playing (and eventually start a new song), but the user should be able to type new commands during that time (like pausing the music). 我想定期检查一首歌是否已停止播放(并最终开始播放一首新歌),但用户在此期间应该能够键入新命令(例如暂停音乐)。 Therefor i tried to use threading.Timer for that. 因此,我尝试使用threading.Timer。 However, it gives me an error if i am inside the function that was called using the timer. 但是,如果我在使用计时器调用的函数中,则会给我一个错误。 the error does not occur when the function was called normally. 正常调用该函数时不会发生该错误。 Heres my (reduced) code: 这是我的(简化)代码:

from threading import Timer
global currentmusic 

def rep():
    b = currentmusic.isplaying() #this is where the error occurs
    if b:
        print "Music is playing"
    else:
        print "Music has stopped"
    t=Timer(5.0,rep) #repeat every 5 seconds
    t.start()
currentmusic=playrandomfile() #loads a song and starts playing it
rep() #call the first time

When rep() is called the second time, it gives me an MCI error in the function isplaying(), saying that it cannot read the device. 当第二次调用rep()时,它在函数isplaying()中给了我一个MCI错误,说它无法读取设备。 My questions: 我的问题:
Am i making a mistake with the way the threading.Timer works? 我在threading.Timer的工作方式上犯了一个错误吗? (and how can i fix it?) Is there another way than threading.Timer to achieve the stuff i want? (以及如何解决?)除了threading.Timer之外,还有其他方法可以实现我想要的东西吗?
My thoughts so far were, that it could be a problem to access currentmusic from another thread, but i am not sure. 到目前为止,我的想法是,从另一个线程访问currentmusic可能是个问题,但我不确定。 Also i dont know how to avoid it. 我也不知道如何避免它。
Thx for helping 感谢帮助

Ive used mp3play in some projects, and it works fine for me. 我已经在某些项目中使用了mp3play,对我来说效果很好。 IMO recursion threading is the problem. IMO递归线程是问题所在。 Just remove the threading timer and leave the rep function call, it wont lag any pc. 只需删除线程计时器并留下rep函数调用,它就不会落后于任何PC。 You should use threading only for raw_input. 您应仅将线程用于raw_input。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM