Advertisement
smeech

Espanso add, from command line

Mar 21st, 2024 (edited)
197
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. # Python script to add Espanso trigger:/replace: pairs
  2. # Usage: python script.py <trigger> <replace> [filename]
  3.  
  4. import subprocess
  5. import sys
  6. import os
  7.  
  8. def append_to_file(trigger, replace, filename):
  9.     # Set default filename if not provided
  10.     if not filename:
  11.         filename = "add.yml"
  12.  
  13.     # Set path to the output file
  14.     config_path = os.path.expanduser("~/.config/espanso/match/")
  15.     output_file = os.path.join(config_path, filename)
  16.  
  17.     # Check if the file exists, if not, create it including "matches:" line
  18.     if not os.path.isfile(output_file):
  19.         with open(output_file, "w") as file:
  20.             file.write("matches:\n")    
  21.  
  22.     # Execute espanso match list command and capture its output
  23.     try:
  24.         output = subprocess.check_output(["espanso", "match", "list"], text=True)
  25.     except subprocess.CalledProcessError as e:
  26.         print("Error executing espanso command:", e)
  27.         sys.exit()
  28.  
  29.     # Check if any line matches the condition
  30.     existing_match = None
  31.     for line in output.split('\n'):
  32.         if line.startswith(trigger + " - "):
  33.             existing_match = line
  34.             break
  35.  
  36.     # If existing match found, print it and exit
  37.     if existing_match:
  38.         print("Found existing match for the trigger:")
  39.         print(existing_match)
  40.         sys.exit()
  41.  
  42.     # Append content to the file
  43.     with open(output_file, "a") as file:
  44.         file.write(f"  - trigger: {trigger}\n")
  45.         file.write(f"    replace: {replace}\n")
  46.  
  47.     print(f"Content appended successfully to {output_file}.")
  48.  
  49. if __name__ == "__main__":
  50.     # Check if trigger and replace are provided
  51.     if len(sys.argv) < 3:
  52.         print("Usage: python script.py <trigger> <replace> [filename]")
  53.         sys.exit(1)
  54.  
  55.     trigger = sys.argv[1]
  56.     replace = sys.argv[2]
  57.     filename = sys.argv[3] if len(sys.argv) > 3 else None
  58.  
  59.     append_to_file(trigger, replace, filename)
  60.  
Advertisement
Comments
  • smeech
    261 days
    Comment was deleted
Add Comment
Please, Sign In to add comment
Advertisement