Skip to content

Instantly share code, notes, and snippets.

@ivankeller
Last active June 20, 2023 20:57
Show Gist options
  • Save ivankeller/1bdf5dbbf551c1e891d7f9ccba0d3f9c to your computer and use it in GitHub Desktop.
Save ivankeller/1bdf5dbbf551c1e891d7f9ccba0d3f9c to your computer and use it in GitHub Desktop.
a python script that fake a key stroke to keep the system alive
#!/bin/env python3
import sys
from threading import Event
from keyboard import press, add_hotkey, remove_hotkey
from time import sleep
from typing import Union
PERIOD = 2.0
TOGGLING_KEY = 'alt+t'
TERMINATING_KEY = 'esc'
def terminate(flag: dict):
flag['active'] = True
print("Terminating gently... ", end='')
def toggle_activation(flag: dict):
if not flag['active']:
flag['active'] = True
print("Activated.")
else:
flag['active'] = False
print("Deactivate.")
def keep_alive(key: str):
lock = Event()
toggling_flag = {'active': True}
termination_flag = {'active': False}
try:
add_hotkey(TOGGLING_KEY, toggle_activation, args=(toggling_flag,))
add_hotkey(TERMINATING_KEY, terminate, args=(termination_flag,))
while not termination_flag['active']:
if termination_flag['active']:
break
if toggling_flag['active']:
press(key)
print(f'Pressed key: {key}')
else:
print('Deactivated.')
_ = lock.wait(timeout=PERIOD)
except Exception as e:
print('Error on keep_alive: {}'.format(e))
def main():
try:
print('Running...')
keep_alive('pause')
print('done.')
except KeyboardInterrupt:
pass
except Exception as e:
print('Error on main: {}'.format(e))
print('Stopped.')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment