Created
February 5, 2024 08:23
-
-
Save louisswarren/f0f30bc512f08b38a2685983945a9b95 to your computer and use it in GitHub Desktop.
Map command line arguments to function arguments in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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