Created
October 5, 2015 16:40
-
-
Save ankon/5c56cbddf83bd87fc9ed to your computer and use it in GitHub Desktop.
Python Magic ...
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
usage: test.py foo [-h] [-a {bar}] | |
test.py foo: error: argument -a/--argument: invalid choice: ' bar' (choose from 'bar') | |
Exception - short | |
usage: test.py [-h] {foo} ... | |
test.py: error: unrecognized arguments: --argument bar | |
Exception - long | |
bar |
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
from argparse import ArgumentParser | |
def foo(v): | |
print v.argument | |
pass | |
def main(*args): | |
parser = ArgumentParser() | |
subparsers = parser.add_subparsers() | |
foo_parser = subparsers.add_parser('foo') | |
foo_parser.add_argument('-a', '--argument', choices=['bar'], help='An argument with short and long forms') | |
foo_parser.set_defaults(func=foo) | |
try: | |
parsed = parser.parse_args(['foo', '-a bar']) | |
parsed.func(parsed) | |
except: | |
print "Exception - short" | |
try: | |
parsed = parser.parse_args(['foo', '--argument bar']) | |
parsed.func(parsed) | |
except: | |
print "Exception - long" | |
try: | |
parsed = parser.parse_args(['foo', '--argument', 'bar']) | |
parsed.func(parsed) | |
except: | |
print "Exception - long/split" | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment