Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting computer/program shutdown in Python?

Tags:

python

windows

I have a Python script that runs in a loop regularly making adjustments to my lighting system. When I shut down my computer, I'd like my script to detect that, and turn off the lights altogether.

How do I detect my computer beginning to shut down in Python?

Or, assuming Windows sends Python a "time to shut down" notice, how do I intercept that to kill my lights and exit the loop?

like image 956
Malcolm Crum Avatar asked Apr 22 '13 07:04

Malcolm Crum


People also ask

How do you shutdown a program in Python?

To shut down the computer/PC/laptop by using a Python script, you have to use the os. system() function with the code “ shutdown /s /t 1 ” . Note: For this to work, you have to import os library in the ide. If you don't have it, then ' pip install os ' through the Command Prompt.

What is the code for shutdown?

To shutdown immediately use "C:\\WINDOWS\\System32\\shutdown -s -t 0".

What is shutdown function?

To shut down or power off a computer is to remove power from a computer's main components in a controlled way. After a computer is shut down, main components such as CPUs, RAM modules and hard disk drives are powered down, although some internal components, such as an internal clock, may retain power.


2 Answers

This is the wrong way to go about performing action at system shutdown time. The job of the shutdown process is to stop running processes and then switch off power; if you try to detect this happening from within your program and react by getting some last action in, it's a race between the OS and your program who gets to go first. More likely than not your program will have been stopped before it managed to perform the necessary action.

Instead, you should hook into the normal protocol for doing things at shutdown. This will tell the shutdown utility to send an explicit signal to your program and wait for it to be acknowledged, which gives you enough time (within reason) to do what you have to do. How exactly to register to be notified varies with the OS, so this is more of an OS-specific question rather than a Python question.

like image 164
Kilian Foth Avatar answered Nov 02 '22 23:11

Kilian Foth


You should react to the WM_ENDSESSION message.

This message is sent when the user logs off or the computer gets shut down.

If you want to react to Sleep/Hibernate as well, you'll need to handle WM_POWERBROADCAST with PBT_APMSUSPEND.

But I don't know how to do that in python. I guess it depends on your windowing framework since you need have a windows/a message loop to receive messages.

like image 25
CodesInChaos Avatar answered Nov 02 '22 23:11

CodesInChaos