การใช้ argparse ใน Python3

Example

The following code is a Python program that takes a list of integers and produces either the sum or the max:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Assuming the Python code above is saved into a file called prog.py, it can be run at the command line and provides useful help messages:

$ python3 prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
  N           an integer for the accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)

When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:

$ python3 prog.py 1 5 3 2 4
5
$ python3 prog.py 1 5 3 2 4 --sum
15

If invalid arguments are passed in, it will issue an error:

$ python3 prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'
$ python3 prog.py
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: the following arguments are required: N

Example2

#!/usr/bin/python3

import argparse

if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument('folder', help='Path to the folder to scan')
        parser.add_argument('output', help='Path of the output file without the extension')
        parser.add_argument('-f', '--format', help='Format of the output', default='pdf', \
                choices=['bmp', 'gif', 'jpg', 'png', 'pdf', 'svg'])
        parser.add_argument('-v', '--view', action='store_true', help='View the graph')
        parser.add_argument('-c', '--cluster', action='store_true', help='Create a cluster for each subfolder')
        parser.add_argument('--cluster-labels', dest='cluster_labels', action='store_true', help='Label subfolder clusters')
        parser.add_argument('-s', '--strict', action='store_true', help='Rendering should merge multi-edges', default=False)
        args = parser.parse_args()
        print(args.folder)
        print(args.cluster)
        print(args.cluster_labels)
        print(args.strict)
        print(args.format)
        print(args.output)
$ ./prog.py ip_folder file_out -c -f png
ip_folder
True
False
False
png
file_out

ดู help

$ ./prog.py -h
usage: prog.py [-h] [-f {bmp,gif,jpg,png,pdf,svg}] [-v] [-c]
               [--cluster-labels] [-s]
               folder output

positional arguments:
  folder                Path to the folder to scan
  output                Path of the output file without the extension

optional arguments:
  -h, --help            show this help message and exit
  -f {bmp,gif,jpg,png,pdf,svg}, --format {bmp,gif,jpg,png,pdf,svg}
                        Format of the output
  -v, --view            View the graph
  -c, --cluster         Create a cluster for each subfolder
  --cluster-labels      Label subfolder clusters
  -s, --strict          Rendering should merge multi-edges

ไม่ใส่ค่าให้ แล้ว error

$ ./prog.py
usage: prog.py [-h] [-f {bmp,gif,jpg,png,pdf,svg}] [-v] [-c]
               [--cluster-labels] [-s]
               folder output
prog.py: error: the following arguments are required: folder, output