Docem
Docem

Reputation: 23

How can I run a command once I close an app in Python?

I want a video to play when I close opera browser, my current code works but it repeats if opera is closed. What I want is if I close opera, it will run only once when I close it, nothing more. Here's my current code:

# Import module
import wmi
from playsound import playsound
import os
import time
from os import startfile

while True:
    # Initializing the wmi constructor
    f = wmi.WMI()
    
    flag = 0
    
    # Iterating through all the running processes
    for process in f.Win32_Process():
        if "opera.exe" == process.Name:
            print("Application is Running")
            playsound('C:/Users/USER/Desktop/pyworkspace/waltuh3.mp3')
            flag = 1
            break
    
    if flag == 0:
        print("Application is not Running")
        class Video(object):
            def __init__(self,path):
                self.path = path

            def play(self):
                startfile(self.path)

        class Movie_MP4(Video):
            type = "MP4"

        movie = Movie_MP4(r"C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\POLAR_BEAR.mp4")
        movie.play()

    time.sleep(3)

Upvotes: 2

Views: 70

Answers (1)

Xiddoc
Xiddoc

Reputation: 3628

You should keep a reference to the last checked 'state' (whether Opera was running or not). Then, you check if it has changed since the last iteration. If in the previous iteration, Opera was running, and in the current iteration, it is now not running, then we can say that Opera was closed between these 2 iterations.

I didn't test this code but it should work like this:

def is_opera_running() -> bool:
    # Iterating through all the running processes
    for process in wmi.WMI().Win32_Process():
        # If we found opera, then return True
        if "opera.exe" == process.Name:
            print("Application is Running")
            playsound('C:/Users/USER/Desktop/pyworkspace/waltuh3.mp3')
            return True
    # We didn't find opera...
    return False

# Get the initial state
last_state = is_opera_running()
while True:
    # Get the new state
    new_state = is_opera_running()
    
    # We will check if Opera is NOT running now
    # AND if the last time we checked, it WAS running
    if not new_state and last_state:
        print("Application is not Running")
        class Video(object):
            def __init__(self,path):
                self.path = path

            def play(self):
                startfile(self.path)

        class Movie_MP4(Video):
            type = "MP4"

        movie = Movie_MP4(r"C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\POLAR_BEAR.mp4")
        movie.play()

    # Then update the old state to the new state
    last_state = new_state

    time.sleep(3)

Upvotes: 1

Related Questions