Python Command Line Arguments


Python can parse command line arguments. One of the ways to do that is using the argparse module. You can also use the sys module for reading command line arguments.

In this article you will learn how to use command line arguments with Python using both of these modules.

Related course: Complete Python Programming Course & Exercises

Parsing Command-line arguments using argparse module

argparse is a command line parsing library. argparse is an optparse-inspired command-line parsing library that functions:

1: Handling optional and location parameters 2: Generation of usage messages 3: Support for the derivation of sub-parsers

argparse contains the following public classes

ArgumentParser

The main entry point for command-line resolution. As shown in the example above, the add_argument() method is used to populate the parser with the action of optional parameters and position parameters. Then call the parse_args() method to convert the parameters in the command line to objects with attributes.

other classes are not introduced here, specific can be viewed argparse instructions document_

import argparse
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=128, metavar='N',
                    help='input batch size for training (default: 64)') # Fill parameter into parser
args = parser.parse_args()

Type of parameters that may be added to an add_argument:

Positional arguments

Positional arguments are defined in English and can be translated as positioning arguments, which can be used without -.

For example, the code prog.py reads as follows.

parser.add_argument("echo") # Required by default
args = parser.parse_args()
print args.echo

Implementation of python prog.py hahahaha

Output: `hahahahaha'

Optional arguments

The Chinese name of the optional parameter is two ways.

Short parameters specified by a -, such as -h

Mode 2: Long parameters specified by -, such as - -help

Optional parameters in add_argument():
*
'-batch-size' or '-b': long or short parameters
*
type: Type of the parameter
*
default: parameter default
*
help="help information": Execute python prog.py -h and this information will be printed after the parameter.
*
choices: This parameter is used to check the range of input parameters. e.g.: choices=[1,3,5]
*
nargs:** This is required to specify when multiple or 0 parameters are accepted after the option. For example, the -u option accepts 2 parameters, python prog.py -u 1 2

  • A variable that accepts multiple parameters actually gets a LIST, and the incoming default value at this time should also be a LIST.

For example.

parser.add_argument('-b', type=int, default=[7,8,9], metavar='n', nargs=3)
args = parser.parse_args()
print(args.b)

Execute: python args.py -b 1 2 3

Output results

[1,2,3]

metavar: This parameter is used in the HELP message output, such as python prog.py -h, which prints: -batch-size N

Reading Python Command-line arguments using the sys module

Another way to parse parameters: using the sys.argv parameter

import sys
if len(sys.argv) ! = 4:
    print('Usage:')
    print('python train.py datacfg cfgfile weightfile')
    exit()
# sys.argv[0] for python script name
datacfg = sys.argv[1]
cfgfile = sys.argv[2]
weightfile = sys.argv[3]