【问题标题】:How to make Python not to wait for the end of the command?如何让 Python 不等待命令结束?
【发布时间】:2020-07-15 12:02:36
【问题描述】:

我正在制作一个语音助手,当我说“设置闹钟”时,程序会冻结并等待闹钟设置的时间。所以在闹钟响起之前我无法与助手通话。
这是代码

if 'alarm' in said:
    engine.say('Set')
    engine.runAndWait()
    now = datetime.datetime.now()
    alarm_time = datetime.datetime.combine(now.date(), datetime.time(int(said)))
    time.sleep((alarm_time - now).total_seconds())
    os.system("start alarm.mp3")

如何忽略它或对程序进行一些操作以使其不会冻结?也许还有其他设置闹钟的方法?
我们将不胜感激!

【问题讨论】:

  • 这能回答你的问题吗? How to start a background process in Python?
  • 使用subprocess 模块,而不是os.system
  • @chepner 你是说这个吗? os.system("start alarm.mp3")
  • 是的。 p = subprocess.Popen(["start", "alarm.mp3"]) 立即返回,在后台运行命令。
  • 不,它不起作用

标签: python datetime time alarm assistant


【解决方案1】:

您可以创建一个thread,它会在指定的时间内sleep。休眠线程不会阻塞主线程,所以它会继续执行。

import threading, time, os

def thread_func(seconds):
    time.sleep(seconds)
    os.system("start alarm.mp3")

threading.Thread(
    target=thread_func,
    args=((alarm_time - now).total_seconds(), ),
    daemon=True
).start()
# Do something else here

os.system 阻止执行,但应该相当快。

【讨论】:

  • 上面写着args=((alarm_time - now).total_seconds(), ), NameError: name 'alarm_time' is not defined
  • 我应该保留这个吗? alarm_time = datetime.datetime.combine(now.date(), datetime.time(int(said)))
  • @AlexZab,当然可以 - 您应该自己指定。只需从您的代码中复制它即可。
  • 现在是File "Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File ".py", line 124, in thread_func time.sleep(seconds) AttributeError: 'list' object has no attribute 'sleep'
  • @AlexZab,显然,time 是你代码中的一个列表。这就是为什么不应该重用标准函数/模块的名称来命名它们的变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
相关资源
最近更新 更多