Receive a signal when waking or suspending?

Skip Montanaro skip.montanaro at gmail.com
Mon Apr 25 12:21:22 EDT 2022


> https://duckduckgo.com/?t=ffab&q=python+up+time pointed-out the
> "uptime — Cross-platform uptime library"
> - TLDR; I'm not sure if "uptime" and "boot" relate only to a
> 'cold-start' or if they include bringing the machine out of 'stand-by'
> or 'hibernation'

Yeah, that won't help. uptime(1) gives the time since the last boot.
Wake/suspend doesn't change the system's notion of boot time.

> https://duckduckgo.com/?t=ffab&q=python+battery+status pointed-out
> several ideas which require MS-Windows, but apparently the psutil
> library could be bent to your will:
>
https://www.geeksforgeeks.org/python-script-to-shows-laptop-battery-percentage/

I actually already have psutil installed. It gives you details about
various system bits (like battery status, which is why I installed it). It
doesn't seem to have anything that will notify about state changes, just
the current state (or — for example — continuous values like the battery
state of charge). I didn't see anything regarding wake/suspend, but I might
have missed it. Since my tool can't run while the system is suspended, it
would always see the system as "awake" but not know for how long it was in
that state. (I'm sure I could track in my tick routine and pay attention to
unusually long gaps.)

I think Marco's response gives me a bit better handle on what I need(*). Maybe
just an easier way to do things. For example, just before suspending and
just after waking, all scripts in /usr/lib/systemd/system-sleep/ are
executed. The only difference is the arguments with which they are called.
A script to suit my needs can just write a stream of records with
timestamps. It took just a minute or so:

#!/bin/sh

echo "`date --iso-8601=seconds` $1 $2" >> /tmp/suspensions
chmod 0644 /tmp/suspensions

Here's what /tmp/suspensions looks like after a couple cycles:

root at montanaro:/usr/lib/systemd/system-sleep# cat /tmp/suspensions
2022-04-23T19:17:41-05:00 pre suspend
2022-04-23T19:17:54-05:00 post suspend
2022-04-23T19:18:48-05:00 pre suspend
2022-04-23T19:19:04-05:00 post suspend


My tool can monitor that file for changes and keep track of the times of
state changes. It can thus track rest intervals across system suspensions
and know if I've been resting for a long enough period of time to allow me
to subject my wrists to further agony
<https://github.com/smontanaro/python-bits/blob/master/src/watch.py> with
the keyboard and mouse.

Skip

(*) man systemd-sleep contains this admonition:

Note that scripts or binaries dropped in /lib/systemd/system-sleep/ are
intended for local use only and *should be considered hacks*. If
applications want to react to system suspend/hibernation and resume,
they should
rather use the Inhibitor interface[1].


A hack should suit my needs just fine. I'll leave more elegant solutions to
others. :-)


More information about the Python-list mailing list