How to use Python argparse

I added. What to watch out for in the argparse test.


Moved to here and updated.


Script argument specifications

I want to specify the argument of a certain script as follows.

The result of implementing such specifications using argparse and displaying with --help is as follows. Make a step-by-step note of this implementation from the next chapter.

$ ./photosort.py --help
usage: photosort.py [-h] [-d [PATH_ROOT_DST]]
                    [-e SORT_FILES_EXTENTIONS [SORT_FILES_EXTENTIONS ...]]
                    [--debug]
                    path_root_src

This script is ...

positional arguments:
  path_root_src         Directory path where your taken photo files are
                        located.

optional arguments:
  -h, --help            show this help message and exit
  -d [PATH_ROOT_DST], --path-root-dst [PATH_ROOT_DST]
                        Directory path where you want to create date folder
                        and locate photo files. (default: same as source
                        directory)
  -e SORT_FILES_EXTENTIONS [SORT_FILES_EXTENTIONS ...], --sort-files-extentions SORT_FILES_EXTENTIONS [SORT_FILES_EXTENTIONS ...]
                        Extentions of file which you want to sort. (default:
                        jpg)
  --debug               debug mode if this flag is set (default: False)

First initialization

I think that there is no problem for most uses with the defaults other than description. Parameters that you would normally use, such as add_help (adding the -h / –help option to the parser), are pre-enabled.

initialize


parser = argparse.ArgumentParser(description='This script is ...')

Add argument

Part 1

Parameters that can be left at the default settings are also specified. (Because it is troublesome to know what the default is without looking at the help)

src directory path must be specified

Specify the name'path_root_src' without-or-in the first argument of add_argument, and specify None in nargs. This will result in a too few argument error if no arguments other than the-and-options are specified in the script. If nargs is set to'?' And specified in combination with parameters such as default and const, the script can be executed without error.

add_argument


parser.add_argument('path_root_src', \
        action='store', \
        nargs=None, \
        const=None, \
        default=None, \
        type=str, \
        choices=None, \
        help='Directory path where your taken photo files are located.', \
        metavar=None)

The first argument string'path_root_src' specified here is used as the attribute name of the Namespace object returned by ʻargs = parser.parse_args () called at the final finish. In other words, "/ Users / test / Pictures" is stored in ʻargs.path_root_src when executed as follows.

$ ./photosort.py /Users/test/Pictures

Part 2

Specifying the dst directory path is not mandatory

Specify two types of option strings in the first argument of add_argument and'?' In nargs. This will take one argument from the command line if possible and use it as the attribute name'path_root_dst' for the Namespace object returned by ʻargs = parser.parse_args () `and set the value of the argument to that attribute. If the option argument itself does not exist (-d itself is not specified), the default value is passed. An optional argument is specified, followed by the value of const if there are no command line arguments. In the case of the example below, both are None, so it doesn't make much sense ...

add_argument


parser.add_argument('-d', '--path-root-dst', \
        action='store', \
        nargs='?', \
        const=None, \
        default=None, \
        type=str, \
        choices=None, \
        help='Directory path where you want to create date folder and locate photo files. (default: same as source directory)', \
        metavar=None)

Part 3

I want to specify multiple extensions of the target file

Specify two types of option strings in the first argument of add_argument and'+' in nargs. This requires at least one command line argument, which results in a too few argument error if the condition is not met. However, the above error occurs only when -e is specified but the command line argument is not specified. If -e itself is not specified, the ['jpg'] specified in default will be used and no error will occur.

add_argument


parser.add_argument('-e', '--sort-files-extentions', \
        action='store', \
        nargs='+', \
        const=None, \
        default=['jpg'], \
        type=str, \
        choices=None, \
        help='Extentions of file which you want to sort. (default: jpg)', \
        metavar=None)

Part 4

I don't usually want to print print statements for debug on stdout

If an optional argument is specified and you simply want it to have True or False, you can do so by specifying'store_true'or'store_false' in action. If this script is run with --debug, then True will be stored in the attribute name ʻargs.debug of the Namespace object returned by ʻargs = parser.parse_args (), which is called at the final finish. ..

add_argument


parser.add_argument('--debug', \
        action='store_true', \
        help='debug mode if this flag is set (default: False)')

Final finish

Convert the arguments specified so far to an object, assign it to the attribute of the Namespace object, and have that object returned. By default, the argument string is taken from sys.argv, so you don't need to specify anything in the argument here.

parse_args


args = parser.parse_args()

Execution result

You can see that the attribute with the name specified by add_argument has been added to the Namespace object returned by parse_args.

(Pdb) b 112
Breakpoint 1 at /Users/dodo5522/Development/manage_media_data/photosort.py:112
(Pdb) c
> /Users/dodo5522/Development/manage_media_data/photosort.py(112)<module>()
-> args = parser.parse_args()
(Pdb) n
(Pdb) dir(args)
['__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_args', '_get_kwargs', 'debug', 'path_root_dst', 'path_root_src', 'sort_files_extentions']
(Pdb) args.debug
(Pdb) print args.debug
False
(Pdb) print args.path_root_dst
/Users/dodo5522/Public
(Pdb) print args.path_root_src
/Users/dodo5522/Pictures
(Pdb) print args.sort_files_extentions
['jpg', 'png', 'mov']
(Pdb)

Recommended Posts

How to use Python argparse
python3: How to use bottle (2)
[Python] How to use list 1
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
Python: How to use async with
[Python] How to use Pandas Series
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
[Python] How to use Typetalk API
How to use xml.etree.ElementTree
How to use Python-shell
[Python] Summary of how to use pandas
[Introduction to Python] How to use class in Python?
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to install Python
How to use Pandas 2
How to install and use pandas_datareader [Python]
How to use Virtualenv
How to use pytest_report_header
[python] How to use __command__, function explanation
How to install python
How to use Bio.Phylo
How to use SymPy
[Python] How to use import sys sys.argv
How to use x-means
How to use WikiExtractor.py
How to use IPython
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
How to use virtualenv
[Python2.7] Summary of how to use unittest
How to use Matplotlib
How to use iptables
python: How to use locals () and globals ()
How to use numpy
How to use __slots__ in Python class
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use "deque" for Python data
How to use python-kabusapi
How to use Python zip and enumerate
[Python] Understand how to use recursive functions