Advertisement
Toumo

auto_code_runner_listener.py

Apr 7th, 2023 (edited)
781
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. # Runs the last-modified script (if its format is a runner_map key) found in search_dir in the event of an esc key press followed by a tab key press.
  2. # Meant to be used alongside Vim, mapping a tab press while on normal mode to :w or :update using vimscript (e.g. nnoremap <buffer> <tab> :w <CR>).
  3.  
  4. import os
  5. import subprocess
  6. from time import time, sleep
  7. from pynput import keyboard
  8.  
  9. search_dir = "/home/tomo/Documents"
  10. runner_map = {"py": lambda path: f"time python -u '{path}'",
  11.               "hs": lambda path: f"time runghc '{path}'",}
  12.  
  13. def path_to_last_mod_in_dir(search_dir: str, file_formats: list[str]) -> str:
  14.     fmt_regex = r".*\.\(" + r"\|".join(file_formats) + r"\)"
  15.     find_cmd = ["find", search_dir, "-regex", fmt_regex]
  16.     path_list = subprocess.run(find_cmd, stdout=subprocess.PIPE).stdout.decode("utf-8").split("\n")[:-1]
  17.     return sorted(path_list, key = os.path.getmtime)[-1]
  18.  
  19. def run_file(path: str, runner_map: dict, print_timestamp: bool = False) -> None:
  20.     fmt = path.split(".")[-1]
  21.     if print_timestamp: os.system("printf '\n--- %(%H:%M:%S)T ---\n\n'")
  22.     if path != os.path.abspath(__file__): os.system(runner_map[fmt](path))
  23.  
  24. def on_press(key):
  25.     global pressed_esc
  26.     global search_dir
  27.     global runner_map
  28.     global path
  29.     if pressed_esc and key == keyboard.Key.tab:
  30.         sleep(1) # Waits for Vim to finish saving
  31.         if not path or os.path.getmtime(path) < time() - 10:
  32.             path = path_to_last_mod_in_dir(search_dir, runner_map.keys())
  33.         run_file(path, runner_map, print_timestamp=True)
  34.     pressed_esc = key == keyboard.Key.esc
  35.  
  36. path = ""
  37. pressed_esc = False
  38. k_listener = keyboard.Listener(on_press = on_press)
  39. k_listener.start()
  40. while True: pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement