Learning using argparse module on Python3
Make an argparse.py file
At first, make a file that name is argparse.py
file by any text editor.
Open the official document on your browser
Aliases
Japanese
Argparse チュートリアル — Python 3.6.5 ドキュメント
English
Argparse Tutorial — Python 3.6.5 documentation
Make the most simple script
Code is bellow.
# coding: utf-8 import argparse parser = argparse.ArgumentParser() parser.parse_args()
Show help.
$ python3 argparse.py -h usage: argparse.py [-h] optional arguments: -h, --help show this help message and exit $
Add positional arguments
Make positional arguments.
Code
# coding: utf-8 import argparse parser = argparse.ArgumentParser() # Positional arguments. parser.add_argument("echo") args = parser.parse_args() print(args)
Show help message.
$ python3 argparse.py -h usage: argparse.py [-h] echo positional arguments: echo optional arguments: -h, --help show this help message and exit $
Run the script with foo
in positional arguments.
$ python3 argparse.py foo Namespace(echo='foo') $
Check what functions in ArgumentParser()
Check in interpreter mode.
$ ipython Python 3.6.4 (default, Jan 6 2018, 11:51:15) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: import argparse In [2]: parser = argparse.ArgumentParser() In [3]: dir(parser) Out[3]: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_action_groups', '_actions', '_add_action', '_add_container_actions', '_check_conflict', '_check_value', '_defaults', '_get_args', '_get_formatter', '_get_handler', '_get_kwargs', '_get_nargs_pattern', '_get_option_tuples', '_get_optional_actions', '_get_optional_kwargs', '_get_positional_actions', '_get_positional_kwargs', '_get_value', '_get_values', '_handle_conflict_error', '_handle_conflict_resolve', '_has_negative_number_optionals', '_match_argument', '_match_arguments_partial', '_mutually_exclusive_groups', '_negative_number_matcher', '_option_string_actions', '_optionals', '_parse_known_args', '_parse_optional', '_pop_action_class', '_positionals', '_print_message', '_read_args_from_files', '_registries', '_registry_get', '_remove_action', '_subparsers', 'add_argument', 'add_argument_group', 'add_help', 'add_mutually_exclusive_group', 'add_subparsers', 'allow_abbrev', 'argument_default', 'conflict_handler', 'convert_arg_line_to_args', 'description', 'epilog', 'error', 'exit', 'format_help', 'format_usage', 'formatter_class', 'fromfile_prefix_chars', 'get_default', 'parse_args', 'parse_known_args', 'prefix_chars', 'print_help', 'print_usage', 'prog', 'register', 'set_defaults', 'usage'] In [4]:
We can see a lot of functions.
And there is add_argument
function.
There is add_argument()
method document.
Japanese
16.4. argparse — コマンドラインオプション、引数、サブコマンドのパーサー — Python 3.6.5 ドキュメント
Engelish
Add help detail message.
Code changes...
# coding: utf-8 import argparse parser = argparse.ArgumentParser() # Positional arguments. parser.add_argument("echo", help="echo the string you use here") args = parser.parse_args() print(args)
Only add help=
option.
Run this.
$ python3 argparse.py -h usage: argparse.py [-h] echo positional arguments: echo echo the string you use here optional arguments: -h, --help show this help message and exit $
Added echo argument message. OK, we can add posisional argument message!
Add argument type in positional argument.
Code is bellow.
# coding: utf-8 import argparse parser = argparse.ArgumentParser() # Positional arguments. parser.add_argument("echo_num", help="echo the number you use here", type=int) args = parser.parse_args() print(args)
Run this help.
$ python3 argparse.py -h usage: argparse.py [-h] echo_num positional arguments: echo_num echo the number you use here optional arguments: -h, --help show this help message and exit $
OK, it seems good.
Run the script with 2
that is positional argument.
$ python3 argparse.py 2 Namespace(echo_num=2) $
OK, next. I will give test
string to this script.
$ python3 argparse.py test argparse.py: error: argument echo_num: invalid int value: 'test' shell returned 2 $
I got an error with helpfull message. It's good behavior.
Use optional arguments.
Make optional argument sample.
# coding: utf-8 import argparse parser = argparse.ArgumentParser() # Optional arguments parser.add_argument("--verbose", help="increase output verbosity") args = parser.parse_args() if args.verbose: print("verbosity turned on")
parser.add_argument()
is same.
It is EASY!
Run the script.
$ python3 argparse.py -h usage: argparse.py [-h] [--verbose VERBOSE] optional arguments: -h, --help show this help message and exit --verbose VERBOSE increase output verbosity
Run the script with optional argument.
$ python3 argparse.py --verbose 1 verbosity turned on
args.verbose
becomes True, run the print function.
It seems good!
Customize!
Change to get True
or False
on --verbose
option. Now, --verbose
opiton is able to get integer values.
Code bellow.
# coding: utf-8 import argparse parser = argparse.ArgumentParser() # Optional arguments parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print("verbosity turned on")
Run the script with -h
.
$ python3 argparse.py -h usage: argparse.py [-h] [--verbose] optional arguments: -h, --help show this help message and exit --verbose increase output verbosity
Help text has changed.
Short options
Easy
# coding: utf-8 import argparse parser = argparse.ArgumentParser() # Optional arguments parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print("verbosity turned on")
Only add "-v"
option. It's so easy!
Run the script with -h
option.
$ python3 argparse.py -h usage: argparse.py [-h] [-v] optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity
Help message has changed!
Thank you!