Skip to content

Instantly share code, notes, and snippets.

@blink1073
Last active August 29, 2015 14:08
Show Gist options
  • Save blink1073/2355d1bb04df75ddb1a0 to your computer and use it in GitHub Desktop.
Save blink1073/2355d1bb04df75ddb1a0 to your computer and use it in GitHub Desktop.
Magic Arg Parser
import optparse
import shlex
import ast
def split_args(cmd):
args = shlex.split(cmd)
new_args = []
temp = ''
for arg in args:
if arg.startswith('-'):
new_args.append(arg)
elif temp:
arg = temp + ' ' + arg
try:
arg = eval(arg)
except:
temp = arg
else:
new_args.append(arg)
temp = ''
elif arg.startswith(('(', '[', '{')) or '(' in arg:
temp = arg
else:
try:
arg = eval(arg)
except:
pass
new_args.append(arg)
if temp:
new_args.append(temp)
return new_args
parser = optparse.OptionParser()
parser.add_option('-f', action="store", dest="fname")
cmd = "-f flag this is the rest of the command"
print(parser.parse_args(split_args(cmd)))
cmd = "function_name [1, 2, 3, 4]"
print(parser.parse_args(split_args(cmd)))
cmd = "range(1, 10)"
print(parser.parse_args(split_args(cmd)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment