Skip to content

Instantly share code, notes, and snippets.

@cassc
Created October 4, 2021 03:22
Show Gist options
  • Save cassc/4ec8dbbdf3d1da262f3783387bbf098c to your computer and use it in GitHub Desktop.
Save cassc/4ec8dbbdf3d1da262f3783387bbf098c to your computer and use it in GitHub Desktop.
Capture power button event
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