Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Created February 5, 2024 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisswarren/f0f30bc512f08b38a2685983945a9b95 to your computer and use it in GitHub Desktop.
Save louisswarren/f0f30bc512f08b38a2685983945a9b95 to your computer and use it in GitHub Desktop.
Map command line arguments to function arguments in python
import sys
def foo(*args, **kwargs):
argstr = list(map(repr, args))
kwargstr = [f'{key}={repr(value)}' for key, value in kwargs.items()]
print("foo(", ", ".join(argstr + kwargstr), ")", sep="")
def easyarg(f):
opts = {}
for i in range(1, len(sys.argv)):
arg = sys.argv[i]
if arg == '--':
return f(*sys.argv[i+1:], **opts)
elif arg.startswith('--'):
eqpos = arg.find('=')
if eqpos >= 0:
key = arg[2:eqpos]
value = arg[eqpos+1:]
else:
key = arg[2:]
value = True
opts[key] = value
else:
return f(*sys.argv[i:], **opts)
return f(*sys.argv[1:])
if __name__ == '__main__':
easyarg(foo)
"""
$ python3 easyarg.py --start=5 -- --a b c  TSTP ✘  1m 3s  ≡
foo('--a', 'b', 'c', start='5')
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment