Python Argparse: Complete Guide

The argparse module is a module in the Python standard library used for parsing command-line arguments. Here is the basic usage of the argparse module:

  1. Import the argparse module.
  2. import the argparse module
  3. Instantiate an ArgumentParser object.
  4. One option is:
    – Create an argument parser with the name “parser” using the argparse module.
  5. Add command line arguments:
  6. – Specify ‘name’ as an argument with the description ‘姓名’.
    – Specify ‘–age’ as an argument with the description ‘年龄’, and parse it as an integer type.
  7. Parse command line arguments.
  8. The arguments are obtained by parsing.
  9. Use command line arguments:
  10. Output the name: args.name
    Output the age: args.age

The complete example code is shown below:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('name', help='姓名')
parser.add_argument('--age', help='年龄', type=int)

args = parser.parse_args()

print('姓名:', args.name)
print('年龄:', args.age)

You can run the script in the command line and pass in the name and age as arguments, for example:

python script.py John --age 25

Output:

姓名: John
年龄: 25

In addition to the basic usage mentioned above, the argparse module also supports more sophisticated parameter settings, such as setting default values for parameters and restricting the range of parameter values. You can refer to the argparse module documentation in the Python official documentation to learn more about usage and examples.

bannerAds