Skip to content

Instantly share code, notes, and snippets.

@SanderRonde
Last active February 9, 2022 22:36
Show Gist options
  • Save SanderRonde/4c0ef890bcf3df89864678dfa7204f08 to your computer and use it in GitHub Desktop.
Save SanderRonde/4c0ef890bcf3df89864678dfa7204f08 to your computer and use it in GitHub Desktop.
Filters passed URI scheme in order for its arguments to be passed to a different program easily
#!/bin/python
import os
import sys
import subprocess
def parse_io():
if len(sys.argv) == 2 and sys.argv[1] == "-h":
print("Pass scheme as first parameter")
print("In this scheme, the scheme itself is removed and the remaining content is split based on the slashes")
print("For example: myscheme://a/b/c would be sliced into ['a', 'b', 'c']")
print("In any following parameters, any text containing #{number} where number is the index in the array above + 1, is replaced with that text")
print("For example in myscheme://a/b/c #1=a, #2=b, #3=c and #0 is the whole scheme")
print("The resulting output is then passed to subprocess, which executes it")
print("Set the TEST environment variable to display the output that would be run instead of running it")
print("Pass the -s flag as the first parameter to avoid splitting of any slashes")
print("For example in myscheme://www.google.com/search #1=www.google.com/search")
exit(0)
if len(sys.argv) < 2:
print("Please pass something to slice")
input('press enter to exit')
exit(1)
if len(sys.argv) < 3:
print("Please pass something to run")
input('press enter to exit')
exit(1)
def get_args():
if sys.argv[1] == '-s':
return sys.argv[2:]
else:
return sys.argv[1:]
def do_slicing():
to_slice = get_args()[0]
if sys.argv[1] == '-s':
return to_slice.split('//')[1:]
else:
return list(filter(lambda item: item, to_slice.split('/')))[1:]
def do_replacing(sliced):
other_args = get_args()[1:]
# Replace all instances of ${num} with that sliced index
for i in range(len(sliced)):
for j in range(len(other_args)):
other_args[j] = other_args[j].replace("#" + str(i + 1),
sliced[i])
for j in range(len(other_args)):
other_args[j] = other_args[j].replace("#0",
sys.argv[1])
return other_args
def do_running(args):
print('running', args)
if "TEST" in os.environ:
exit(0)
try:
subprocess.call(args)
except Exception as e:
print('failed to execute program, got error', e)
input('press enter to exit')
exit(1)
def main():
parse_io()
sliced = do_slicing()
args = do_replacing(sliced)
do_running(args)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment