python - While loop problem, or probably sth else?
问题描述
Soo i am a pupil, and i am quite new to coding. I want to make an app that starts a timer when a game starts (specifically the game Valorant), which i get by searching if the process of the game is running. Then i get notifications by the app every 30 minutes. Finally, when i close the game, the app is supposed to pause the timer and tell me how long i was playing. When i close the game, though, the timer does not stop, and i have discovered that the app never understands that the process has stopped running, even though i use a while loop. This is the code: Thank u in advance!
from win10toast import ToastNotifier import psutil import time import schedule
def show_name(): game = "VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter())
if game == True:
def timer():
game = "VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter())
m = 0
s = 0
while game == True:
time.sleep(1)
s += 1
print(m , s)
if s == 59:
m +=1
s = 0
if m == 30:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for 30 minutes", duration=20)
elif m == 60:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for an hour", duration=20)
elif m == 90:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for 1 hour and 30 minutes", duration=20)
elif m == 120:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for 2 hours", duration=20)
else:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have played for " + str(m) + " minutes and " + str(s) + " seconds!", duration=20)
schedule.every(4).seconds.do(timer)
schedule.every(4).seconds.do(show_name)
while 1: schedule.run_pending() time.sleep(1)
解决方案
The reason why the while loop won't break is you don't change the game variable within the while loop. It means if the game is True at the beginning, while game == True
is the same as while True
loop. You need to revalidate the game in every iteration.
try While"VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter()):
BTW, You can directly write While game:
instead of While game == True
推荐阅读
- c - 这个例外是什么意思?格式 %d 需要类型为“int”的参数,但参数 2 的类型为“long long unsigned int”[-Wformat]
- r - Highcharter 工具提示不适用于许多系列
- javascript - backgroundColor 以空字符串的形式出现,当我设置它的值时不会在屏幕上改变
- javascript - 如何使用 javascript 更改导航上的活动导航栏图标
- linux - 如何抑制 grep 的错误输出,使其仅返回退出状态?
- database - MongoDB:如何处理两个用户同时上传相同的用户名或密码
- github - 我如何从 Github 安装文件
- python - Python:我在为 Instagram 创建机器人时遇到错误,我该如何解决?
- ios - 使用 Swift 在 Firebase 中进行 GeoHash 查询
- excel - Excel VBA AutoFilter 选择过滤器等于 key1 和 key2 最小值的行