Python: Get the Command Line Argument with ArgumentParser

CLI

It is easy to get the command line argument of python shell script with ArgumentParser class.

The ArgumentParser class has following functions:

  • Get the positional required argument
  • Get the optional argument
  • Output the help

If the script executed without required arguments, the ArgumentParser class abort the script.

It is hard work to write above functions by yourself in your own script.

スポンサーリンク

Basic usage

The basic code to use `ArgumentParser` class is following:

import argparse

# Allocate the parser
parser = argparse.ArgumentParser()

# Register arguments to the parser


# Parse command line arguments
# The result will be returned into the args variable.
args = parser.parse_args()


# Get arguments from the args variable.


Write your program description

You can set the description of your program with the description parameter of the initializer.

parser = argparse.ArgumentParser(description: "Demo program of ArgumentParser class")

The description is displayed by --help option.

$ python3 demo.py
usage: demo.py [-h]

Demo program of ArgumentParser class

optional arguments:
  -h, --help  show this help message and exit

Descriptions of programs and arguments can be omitted. However, we recommend that you do not omit it.

Immediately after implementing the code, you know for yourself what the program is. However, after a while you may forget. In addition, if you take over and explain when another person is in charge or when someone uses it, you only need to hand it over.

Parse and Get the Required Argument

Use add_argument() method to parse and get the required argument.

parser.add_argument("value", help="The value of required argument.")

This code add the value argument. You can set the description of the argument to the help parameter. You can omit it.

The passed value can be get with following code:

parser.add_argument("value", help="The value of required argument.")
args = parser.parse_args()

value = args.value
print(value)

The passed values are returned into the args variable. You can get the value with parser.name.

For example, run the demo.py script with ABC, above code will output following:

$ python3 demo.py ABC
ABC

If you run the script without required argument, the script output the error and abort.

$ python3 demo.py
usage: demo.py [-h] value
demo.py: error: the following arguments are required: value

Parse and Get the optional argument

You can also use add_argument() method to parse and get the optional argument.

The optional argument has prefix -.

parser.add_argument("--level", help="The priority level.")

Get the value with following code:

args = parser.parse_args()

level = args.level

You can omit the optional argument. If you run the script without optional argument, the value will be Null.

The optional argument may has multiple names, such as abbreviation. Pass all names to the add_argument() method.

parser.add_argument("-l", "--level", help="The priority level.")

Get the value with following code:

args = parser.parse_args()

level = args.level

Use the optional argument as a flag

If you want to use the optional argument as a flag, write following code:

parser.add_argument("--supermode", action="store_true", help="Run as supermode.")

If you run this script with --supermode, the args.supermode will be True.

Specify the default value

You can set the default value which is used instead of `Null` when the optional argument is not specified.

parser.add_argument("--level", default="1", help="The priority level.")

If you run script without --level, the value will be 1.

Specify the type of the argument

You can specify the type of the argument with `type` parameter.

parser.add_argument("--level", type=int, default="1", help="The priority level.")

The level will be int instead of string.

Specify choices

You can specify choices with choices parameter.

parser.add_argument("--mode", choices=["normal", "super"], help="The running mode.")

The value of --mode will be normal or super. If you specify other value, next error will be output and abort program.

$ python3 demo.py --mode=foo
usage: demo.py [-h] [--mode {normal,super}]
demo.py: error: argument --mode: invalid choice: 'foo' (choose from 'normal', 'super')

Multiple value argument

If you want to make the argument which can accept multiple values such as target files, write following code:

parser.add_argument("target", nargs="*", help="Target Files")

The value of returned from parse_args() method will be an array. The number of values are specified to the nargs parameter. If you write 2, the argument must be 2 values.

If you write *, the argument will be empty or more. If you write +, the argument will be least one value.

Conclusion

The ArgumentParser has more functions, however you can write the code to get the command line argument in most cases with functions explained in this article.

スポンサーリンク
最新情報をチェックしよう!
>現役のプログラマーが書くプログラミング情報

現役のプログラマーが書くプログラミング情報

日々の開発の中での学びや分かったこと、調べたことなどを書いていくブログです。

CTR IMG