Detailed explanation of three command line modules in python of sys. argv argparse click

  • 2021-08-21 21:04:30
  • OfStack

As a scripting language, Python often accepts command-line incoming parameters as scripts, and Python accepts command-line parameters in about three ways. Because it is often used in daily work scenarios, these methods are summarized here.

Command line parameter module

Here, these three modules are used most in the normal work of command line parameter modules: sys. argv, argparse and click. sys. argv and argparse are built-in modules, while click is a third-party module.

sys. argv module (built-in module)

Let's look at a simple example first:


#!/usr/bin/python
import sys

def hello(name, age, sex, *args):
  print("Hello, My name is {name}.".format(name=name))
  print("I'm {age} years old.".format(age=age))
  print("I'm a {sex}".format(sex=sex))

  print("Other word:\n{args}".format(args="\n".join(args)))


if __name__ == "__main__":
  file_name = sys.argv[0]
  name = sys.argv[1]
  age = sys.argv[2]
  sex = sys.argv[3]
  other = sys.argv[4:]
  hello(name, age, sex, *other)

Invoke script:


python test_sysargv.py zhangsan 13 man nibi ss

Script output:

Hello, My name is zhangsan.
I'm 13 years old.
I'm a man
Other word:
nibi
ss

The sys. argv module is not difficult to understand, and the command parameters are passed into the Python script as a list, argv [0] is the name of the script, argv [1] is the first parameter, and so on. Therefore, in the script, you only need to extract the parameters in the list. The above shows the correct call to the Python script, and the following shows the failure of the call.

Error calling script:


python test_sysargv.py zhangsan 13

Error output:


Traceback (most recent call last):
 File "test_sysargv.py", line 16, in <module>
  sex = sys.argv[3]
IndexError: list index out of range

It is also easy to understand the error. The classic list index is out of range, and the list index is out of range and does not pass in enough parameters. Of course you can use try... except to catch errors. However, this approach is too rigid, because the parameters must be entered in the order specified by the script on the command line, so this module uses 1 for 1 scripts that require fewer parameters and are fixed.

argparse Module (Built-in Module)

Let's look at a simple example first:


#!/usr/bin/python
import argparse

parser = argparse.ArgumentParser(description='Test for argparse module.')  #  Build command parameter instances 
parser.add_argument("--name", "-n", help="name attribute:  Non-essential attribute ")
parser.add_argument("--age", "-a", help="age attribute:  Non-essential attribute ")
parser.add_argument("--sex", "-s", help="sex attribute:  Non-essential attribute ")
parser.add_argument("--type", "-t", help="type attribute:  Non-essential attribute ", required=True)
args = parser.parse_args()


def hello(name, age, sex, *args):
  print("Hello, My name is {name}.".format(name=name))
  print("I'm {age} years old.".format(age=age))
  print("I'm a {sex}".format(sex=sex))

  print("Other word:\n{args}".format(args="\n".join(args)))


if __name__ == "__main__":
  print("Format of transfer file: {type}".format(type=args.type))
  if args.name and args.age and args.sex:
    hello(args.name, args.age, args.sex)

Execute the script:


python3 test_argparse.py -t json -n zhangsan -a 13 -s man

Successful script output:

Format of transfer file: json
Hello, My name is zhangsan.
I'm 13 years old.
I'm a man
Other word:

With regard to the use of argparse module, it is necessary to generate an instance of command line parameters first, and then add parameters that need to be obtained from the command line by adding attributes to this object, including which are necessary parameters (required=True) and which are not necessary parameters. At the same time, you can also give help prompts for each parameter (help= "").

In the above example, four attributes,--name and--n, which can be used on the command line at the same time, are added to represent the parameter name. ArgumentParser parses the parameters through the parse_ags () method, checks the command line, and converts each parameter to the appropriate type, so you can also use args. n and args. name to get the parameters in the script. Correspondingly, if the parameter is not passed in, None is obtained in the script.

View help tips for scripts after command line arguments:


python3 test_argparse.py -h
usage: test_argparse.py [-h] [--name NAME] [--age AGE] [--sex SEX] --type TYPE

Test for argparse module.

optional arguments:
 -h, --help      show this help message and exit
 --name NAME, -n NAME name attribute:  Non-essential attribute 
 --age AGE, -a AGE   age attribute:  Non-essential attribute 
 --sex SEX, -s SEX   sex attribute:  Non-essential attribute 
 --type TYPE, -t TYPE type attribute:  Non-essential attribute 

In addition, there are more settings in the attributes of adding command line parameters. For redundant ones, please refer to the official documents of Python, which are marked in detail. It is not expanded here. The summary is that the use of argparse module is very simple, and at the same time, it is 10 points humanized, which also meets the needs of daily work.

click module

Let's start with a simple use example:


#!/usr/bin/python
import click

@click.command()
@click.option("--name", default="zhangsan", help="name attribute:  Non-essential attribute ")
@click.option("--age", help="age attribute", type=int)
@click.option("--sex", help="sex attribute")
@click.option("-t", help="type attribute:  Required attributes ", required=True)
def hello(t, name, age, sex, *args):
  print("Format of transfer file: {type}".format(type=t))
  print("Hello, My name is {name}.".format(name=name))
  print("I'm {age} years old.".format(age=age))
  print("I'm a {sex}".format(sex=sex))

  print("Other word:\n{args}".format(args="\n".join(args)))


if __name__ == "__main__":
  hello()

Execute the script:


python3 test_click.py -t 1 --age 13 --sex man

Script output:

Format of transfer file: 1
Hello, My name is zhangsan.
I'm 13 years old.
I'm a man
Other word:

click module is an excellent open source project of Flask team. Its usage method is very similar to argparse module. It also encapsulates a large number of methods for command line, and users only need to focus on the implementation of code functions.
The difference between click module and argparse module is that click module uses decorator to add command line attributes to functions. Simply speaking, decorator can add functions without modifying original functions. Although decorators are used, the way command-line attributes are added is very similar to the argparse module, including the common parameter meanings in options. It's worth noting that 1 starts by using command () to make the function an interface to the command line.
About the click module is roughly mentioned here, the rest of the interested can go to understand 1.

Summarize

It is worth noting about these three modules that you should choose as close as possible to your own application scenarios, and the reason why you use these modules is that you can really use them conveniently.

The above is a detailed explanation of the three command line modules in python (sys. argv, argparse, click). Please pay attention to other related articles on this site for more information about python command line modules!


Related articles: