首页 > 解决方案 > 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)

标签: pythontimewhile-looptimerpsutil

解决方案


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


推荐阅读