You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 while condition checks (t.tm_sec) != T+(t.tm_sec) — this simplifies to 0 != T. If you enter any non-zero number for T, the condition is true, and the function immediately returns t (exiting the timer entirely). If you enter 0, it jumps to the else block right away without waiting.
  • Unquoted path with spaces: The path C:/Users/Public/Music/Sample Music has a space in it. When using os.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.system command, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:41:20