Last active
October 22, 2018 04:14
-
-
Save CMCDragonkai/849e2dc3d0353d327718ec5eb32e1027 to your computer and use it in GitHub Desktop.
Python Argparse Position and Keyword Arguments #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
#!/usr/bin/env python3 | |
import sys | |
import argparse | |
def main(args): | |
# in python you can call functions with positional or keyword arguments | |
# you can also do something similar with argparse using the below style | |
# note however if you use the type constraint, you'll have to supply custom functions | |
# that understands that argparse.SUPPRESS should be considered as None | |
# you can call this program like | |
# program 1 two 3.0 | |
# program -n 1 -s two --float=3.0 | |
# program 1 -s two --float=3.0 | |
# program 1 two --float=3.0 | |
# program 1 --float=3.0 --string=two | |
# remember that doing this the "keyword parameters" have to be specified after positonal parameters | |
# just like function call syntax | |
# you cannot use them like "options" that before the positional parameters | |
parser = argparse.ArgumentParser() | |
group1 = parser.add_mutually_exclusive_group(required=True) | |
group1.add_argument('-n', '--number', default=None) | |
group1.add_argument( | |
'number', nargs='?', default=argparse.SUPPRESS, help=argparse.SUPPRESS) | |
group2 = parser.add_mutually_exclusive_group(required=True) | |
group2.add_argument('-s', '--string', default=None) | |
group2.add_argument( | |
'string', nargs='?', default=argparse.SUPPRESS, help=argparse.SUPPRESS) | |
group3 = parser.add_mutually_exclusive_group(required=True) | |
group3.add_argument('-f', '--float', default=None) | |
group3.add_argument( | |
'float', nargs='?', default=argparse.SUPPRESS, help=argparse.SUPPRESS) | |
group4 = parser.add_mutually_exclusive_group() | |
group4.add_argument('-o', '--option', default='DEFAULTVALUE') | |
group4.add_argument( | |
'option', nargs='?', default=argparse.SUPPRESS, help=argparse.SUPPRESS) | |
args = parser.parse_args(args) | |
print(args) | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment