lang/python/ MiscSimpleScripts
=== Autohotkey helper Autohotkey is a handy utility for Windows, allowing you to assign actions to arbitrary hotkeys, including mapping things like 'Windows T' to a bash terminal, and 'Windows W' to my usual word processor. There is an awkward quirk whereby applications launched with the Run command from Autohotkey do not always get focus. The fix is the following idiom: {{c
+w::
Run, C:\Program Files (x86)\LibreOffice 5\program\scalc.exe,,,OutputVarPID WinWait, ahk_pid %OutputVarPID% WinActivate, ahk_pid %OutputVarPID% Return }} instead of simply {{c
+w::
Run, C:\Program Files (x86)\LibreOffice 5\program\scalc.exe Return }} thought repeatedly typing this is tedious. The following script takes input of the form: {{c
+w::C:\Program Files (x86)\LibreOffice 5\program\scalc.exe
w::C:\Program Files (x86)\LibreOffice 5\program\swriter.exe
t::C:\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico -
}} and turns it into the 'Run Wat Activate' form shown earlier. The input filename should be of the form 'filename.ahk.in', and this will generate 'filename.ahk', which Autohotkey can then compile to a .exe for you (I then stick this in the Startup folder, either personal, or 'All Users').
Here is the script: {{c
!/usr/bin/env python3
import sys
Template: a format string for the str.format(xxx) method
tmpl = """{:: Run, ,,,OutputVarPID WinWait, ahk_pid %OutputVarPID% WinActivate, ahk_pid %OutputVarPID% Return
"""
Iterate over specified filenames
for s in sys.argv[1:]: if s[-7:] == ".ahk.in": t = s[:-3] # s is input filename, t is output filename with open(s) as f: a = f.read().strip().split("\n") # remove trailing newlines and split o = "" # accumulator string for output for x in a: b = x.split("::",1) # Split at first :: try: o += tmpl.format(*b) # produce and append the output except IndexError: print("Invalid line: ".format(x)) # if no :: present! with open(t,"wt") as g: g.write(o) # write output to file print("Written ".format(t)) else: print("Input file '' must be of form filename.ahk.in".format(s)) }}}%TIME=1486908635