Python定时播放音乐代码无法运行,请求排查错误
Issues in Your Python Timer Code & Fixed Version
Let's break down the problems in your code step by step, then fix it up to work as expected:
- Static time variable: You capture
t = time.localtime(time.time())once at the start, so it never updates as time passes. The loop condition will always use this initial time value, meaning your timer can't track real-time changes at all. - Broken loop logic: Your
whilecondition checks(t.tm_sec) != T+(t.tm_sec)— this simplifies to0 != T. If you enter any non-zero number forT, the condition is true, and the function immediately returnst(exiting the timer entirely). If you enter 0, it jumps to theelseblock right away without waiting. - Unquoted path with spaces: The path
C:/Users/Public/Music/Sample Musichas a space in it. When usingos.system, you need to wrap paths with spaces in quotes, otherwise the system will interpret "Sample" and "Music" as separate arguments and fail to locate the directory. - Incorrect timer logic: Your approach compares the initial second value to
initial-second + T, which doesn't account for clock rollover (e.g., if it's 55 second and you set T=10, 55+10=65 isn't a valid second value).
Here's the fixed code that addresses all these issues:
import time import os def Timer(): T = int(input("Enter desired time for the timer (in seconds) - ")) # Record the start time in seconds since epoch start_time = time.time() # Wait until the elapsed time reaches the input duration while time.time() - start_time < T: # Add a small sleep to reduce unnecessary CPU usage time.sleep(0.1) # Wrap the path in quotes to handle spaces correctly os.system('start "" "C:/Users/Public/Music/Sample Music"') Timer()
Key improvements:
- Uses
time.time()to track elapsed time accurately, avoiding issues with minutes/hours rolling over. - The loop runs until the elapsed time matches your input duration, with a small
time.sleep()to prevent the loop from hogging CPU resources. - Wraps the target path in double quotes inside the
os.systemcommand, so the system recognizes the full path despite the space. - Moves the input inside the function for cleaner structure (you can adjust this if you prefer to pass T as an argument instead).
内容的提问来源于stack exchange,提问作者Yashasav Prajapati
相关产品推荐
相关产品推荐

