import argparse

What is it? When use it?

Python in-built parser inherited from C language

# myls.py
import os
import sys

if len(sys.argv) > 2:
    print('You have specified too many arguments')
    sys.exit()

if len(sys.argv) < 2:
    print('You need to specify the path to be listed')
    sys.exit()

input_path = sys.argv[1]

if not os.path.isdir(input_path):
    print('The path specified does not exist')
    sys.exit()

print('\n'.join(os.listdir(input_path)))

“argparse” library

  • getopt and optparse are old version of parsers
  • The Python argparse library:
    • Allows the use of positional arguments
    • Allows the customization of the prefix chars
    • Supports variable numbers of parameters for a single option
    • Supports subcommands (A main command line parser can use other command line parsers depending on some arguments.)

How to use “argparse”?

  1. Import the Python argparse library
  2. Create the parser
  3. Add optional and positional arguments to the parser
  4. Execute .parse_args()

Examples

1: simple example
2: with subprocess

Resources

SuperMade with Super