- 1 year ago
how can i exit from a running windows program by a python script?
To exit a running Windows program using a Python script, you can use the subprocess
module to launch the program and then terminate it. Here's an example:
pythonimport subprocess
import psutil
# Launch the Windows program
program_path = "C:\\path\\to\\program.exe"
program_process = subprocess.Popen(program_path)
# Terminate the program
for proc in psutil.process_iter():
if proc.name().lower() == "program.exe":
proc.terminate()
break
In this example:
Use the
subprocess.Popen
function to launch the Windows program. Replace"C:\\path\\to\\program.exe"
with the actual path to the program you want to run.The
subprocess.Popen
function starts the program and returns aPopen
object representing the running process.Import the
psutil
module, which provides an interface to retrieve information about running processes.Use
psutil.process_iter()
to iterate over the running processes.Check the name of each process using
proc.name().lower()
and compare it to the name of the program you want to terminate. Adjust the comparison as needed to match the program's name.When the matching process is found, terminate it using
proc.terminate()
.
By combining the subprocess
and psutil
modules, you can launch a Windows program from your Python script and then terminate it when desired.
Note that terminating a program forcefully using proc.terminate()
may result in data loss or unexpected behavior. It's recommended to gracefully exit the program if possible or save any necessary data before terminating it.