gpt4 book ai didi

python 闹钟

转载 作者:太空狗 更新时间:2023-10-30 00:50:58 34 4
gpt4 key购买 nike

在哥哥的帮助下,我制作了这个小闹钟。我昨晚尝试了它,没有使用 nonBlockingRawInput 并且工作正常,但是使用 nonBlockingRawInput 它没有工作。今天我已经试过了,但它们都不起作用!我将使用 nonBlockingRawInput 和“非”文件发布代码。如果您想要没有 nonBlockingRawInput 的代码,请询问。

提前致谢。

报警rpi.py:

import time
import os
from non import nonBlockingRawInput

name = input("Enter your name.")

print("Hello, " + name)

alarm_HH = input("Enter the hour you want to wake up at")
alarm_MM = input("Enter the minute you want to wake up at")

print("You want to wake up at " + alarm_HH + ":" + alarm_MM)

while True:
now = time.localtime()
if now.tm_hour == int(alarm_HH) and now.tm_min == int(alarm_MM):
print("ALARM NOW!")
os.popen("open mpg321 /home/pi/voltage.mp3")
break

else:
print("no alarm")
timeout = 60 - now.tm_sec
if nonBlockingRawInput('', timeout) == 'stop':
break

非.py:

import signal

class AlarmException(Exception):
pass

def alarmHandler(signum, frame):
raise AlarmException

def nonBlockingRawInput(prompt='', timeout=20):
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(timeout)
try:
text = input(prompt)
signal.alarm(0)
return text
except AlarmException:
pass
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ''

最佳答案

我已经研究了您的代码一段时间了。据我所知,您希望能够运行警报,同时还能够在 shell 中键入“stop”以结束程序,为此您可以将警报设为线程。该线程将检查是否该说“ALARM!”了。并打开 mp3。如果用户没有在 shell 中输入停止,线程将休眠并稍后再次检查。

我基本上使用了您的代码并将其放入警报线程类中:

import time
import os
import threading


class Alarm(threading.Thread):
def __init__(self, hours, minutes):
super(Alarm, self).__init__()
self.hours = int(hours)
self.minutes = int(minutes)
self.keep_running = True

def run(self):
try:
while self.keep_running:
now = time.localtime()
if (now.tm_hour == self.hours and now.tm_min == self.minutes):
print("ALARM NOW!")
os.popen("voltage.mp3")
return
time.sleep(60)
except:
return
def just_die(self):
self.keep_running = False



name = raw_input("Enter your name: ")

print("Hello, " + name)

alarm_HH = input("Enter the hour you want to wake up at: ")
alarm_MM = input("Enter the minute you want to wake up at: ")

print("You want to wake up at: {0:02}:{1:02}").format(alarm_HH, alarm_MM)


alarm = Alarm(alarm_HH, alarm_MM)
alarm.start()

try:
while True:
text = str(raw_input())
if text == "stop":
alarm.just_die()
break
except:
print("Yikes lets get out of here")
alarm.just_die()

值得注意的是,当线程休眠时,有:

time.sleep(60)

并且您在 shell 中键入了 stop 线程必须在它意识到它已经死了之前被唤醒,所以最坏的情况是您最终可能会等待一分钟以等待程序关闭!

关于 python 闹钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16325039/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com