- 1 year ago
How to run a program (python ) before system shutdown?
To run a Python program before system shutdown on Windows, you can use the winreg
module to modify the Windows Registry and set up a custom shutdown handler. Here's an example:
pythonimport winreg
import subprocess
def run_before_shutdown():
# Path to your Python executable and script
python_path = r'C:\Python39\python.exe'
script_path = r'C:\path\to\your\script.py'
# Run the Python script
subprocess.call([python_path, script_path])
def register_shutdown_handler():
# Open the Windows Registry
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown', 0, winreg.KEY_ALL_ACCESS)
# Create a new Registry value for the shutdown script
script_path = r'C:\path\to\your\script.py'
winreg.SetValueEx(key, '0', 0, winreg.REG_SZ, script_path)
# Close the Registry
winreg.CloseKey(key)
# Register the shutdown handler
register_shutdown_handler()
# Run your program before shutdown
run_before_shutdown()
In this example:
The
run_before_shutdown()
function represents your Python program that you want to run before the system shuts down. Replace thepython_path
andscript_path
variables with the appropriate paths to your Python executable and script.The
register_shutdown_handler()
function modifies the Windows Registry to set up a custom shutdown script. It opens the appropriate Registry key, creates a new Registry value with the path to your script, and closes the Registry.
Make sure you have the necessary permissions to modify the Windows Registry. It is recommended to run the script with administrative privileges.
After registering the shutdown handler and running your program before shutdown, Windows will execute your Python script before shutting down the system.
Please note that modifying the Windows Registry can have unintended consequences if not done correctly. It's essential to exercise caution and create backups of your Registry before making any changes.