- 1 year ago
Waiting for closing of previously started program
To wait for the closing of a previously started program in Python, you can use the subprocess
module to start the program and then wait for it to exit. Here's an example:
pythonimport subprocess
def start_program():
# Start the program
subprocess.Popen(["program.exe"])
def wait_for_program_exit():
# Wait for the program to exit
process = subprocess.Popen(["tasklist", "/FI", "IMAGENAME eq program.exe"], stdout=subprocess.PIPE)
output = process.stdout.read().decode()
while "program.exe" in output:
process = subprocess.Popen(["tasklist", "/FI", "IMAGENAME eq program.exe"], stdout=subprocess.PIPE)
output = process.stdout.read().decode()
# Start the program
start_program()
# Wait for the program to exit
wait_for_program_exit()
print("Program has exited.")
In this example, the start_program
function starts the program using subprocess.Popen
. The wait_for_program_exit
function continuously checks if the program is still running using the tasklist
command. It retrieves the list of running processes and searches for the program name (program.exe
). If the program is still found in the process list, it continues waiting. Once the program is no longer found in the process list, it exits the loop.
After starting the program, you can call the wait_for_program_exit
function to wait for the program to exit. Once the program has exited, the message "Program has exited" is printed.
Note that this example assumes that the program you are waiting for is named "program.exe". You need to replace it with the actual program name you are waiting for.
Additionally, keep in mind that this approach waits indefinitely until the program exits. If you want to add a timeout or other conditions, you can modify the loop accordingly.