Created
October 4, 2021 03:22
-
-
Save cassc/4ec8dbbdf3d1da262f3783387bbf098c to your computer and use it in GitHub Desktop.
Capture power button event
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import evdev | |
import subprocess | |
from evdev import InputDevice, categorize | |
# To find the path, use `evtest` | |
dev = InputDevice('/dev/input/event2') | |
def ignore_error(func): | |
def myfunc(*args, **kwargs): | |
try: | |
func(*args, **kwargs) | |
except Exception: | |
print('Error ignored') | |
traceback.print_exc(file=sys.stdout) | |
return myfunc | |
def poweroff(): | |
cmd = ['/sbin/shutdown', '-h', 'now'] | |
subprocess.run(cmd) | |
@ignore_error | |
def run(): | |
for event in dev.read_loop(): | |
if event.type == evdev.ecodes.EV_KEY: | |
data = evdev.categorize(event) | |
if data.keystate == 1: | |
print('Shutting down system') | |
poweroff() | |
else: | |
print(f'Ignore event: {event}') | |
if __name__ == '__main__': | |
while True: | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment