Hướng dẫn argparse trong python - argparse trong python

Xin chào các bạn. Hôm nay mình xin phép giới thiệu argparse. Đây là một thư viện có sẵn và sẽ sẽ giúp bạn viết CLI (Command Line Interface) trong Python một cách rất dễ dàng.

Trước tiên, nếu bạn chưa biết CLI là gì, bạn có thể đọc qua tại đây. Đại khái có thể hiểu nó là môi trường mà bạn tương tác với máy tính qua lệnh (Command Line).

1. Argparse để làm gì.

argparse là một thư viện có sẵn trong Python dùng để viết CLI. Khi viết, chương trình của bạn sẽ định nghĩa các tham số cần thiết và argparse sẽ tìm cách truyền các tham số đó từ

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))
1.

Ví dụ, bạn viết 1 phần mềm chuyên dùng để tính toán phức tạp, và bạn viết nó dưới dạng CLI. Người dùng sẽ chạy phần mềm này qua Terminal mà không cần đến giao diện đồ họa (không nút bấm, không cửa sổ).

Ví dụ chương trình của bạn tên là được chứa trong file tên là

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))
2. Vậy người dùng có thể chạy và hiển thị kết quả.

python foo.py arg1 arg2 arg3
result

2. Dùng argparse như thế nào.

Chúng ta sẽ bắt đầu với 1 ví dụ được lấy trực tiếp từ doc của thư viện này.

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))

Bạn lấy code này rồi chạy trong Terminal, kết quả sẽ như sau.

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)

Mình sẽ giải thích từng phần như sau:

1.

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))
3

Bước này không có gì khó hiểu nếu bạn quen với Python hay một số ngôn ngữ khác cú pháp tương tự. Ở đây chúng ta đang

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))
4 , tức đang gọi code từ module argparse sang phiên làm việc hiện tại.

2.

parser = argparse.ArgumentParser(description='Process some integers.')

Ở đây, chúng ta đang tạo ra 1 biến là

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))
6. phần
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))
7 sẽ trả về một object, hay một đối tượng. Từ bước này trở đi biến parser sẽ lưu giữ các thông tin cần thiết để truyền các biến từ CLI vào chương trình Python. Tham số
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))
8 được sử dụng để cung cấp thông tin mô tả chương trình của bạn. Ví dụ ở đây thì
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))
9

Ngoài

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))
8 thì ArgumentParrser còn một số các tham số khác như sau:

  • 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)
    
    1 : Tên của chương trình (Mặc định
    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)
    
    2, đây thường chính là tên file mà bạn lưu code. )
  • 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)
    
    3: Một chuỗi miêu tả cách sử dụng chương trình
  • 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)
    
    4: Một class để tùy chỉnh phần thông tin trợ giúp
  • 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)
    
    5 : Thêm cờ
    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)
    
    6 cho chương trình để thiện phần thông tin trợ giúp
  • 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)
    
    7: Các tham số mặc định truyền vào

3.

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)')

Ở đây, trước hết

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)
8 định nghĩa cách mà các biến từ CLI sẽ được truyền vào Python. Mỗi lần gọi
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)
8 sẽ xử lý một tham số duy nhất.

Ở vị trí đầu tiên (ở trong ví dụ là

parser = argparse.ArgumentParser(description='Process some integers.')
0 hoặc
parser = argparse.ArgumentParser(description='Process some integers.')
1), đây có thể là tên hoặc một cờ bạn sẽ truyền vào.

Các tham số còn lại có chức năng sau:

  • parser = argparse.ArgumentParser(description='Process some integers.')
    
    2: Tên của tham số khi được ghi trong các phần thông tin trợ giúp (ở trong ví dụ là các đoạn
    parser = argparse.ArgumentParser(description='Process some integers.')
    
    3 và
    parser = argparse.ArgumentParser(description='Process some integers.')
    
    4
  • parser = argparse.ArgumentParser(description='Process some integers.')
    
    5 : Kiểu dữ liệu mà tham số truyền vào sẽ được ép thành (ở trong ví dụ là kiểu
    parser = argparse.ArgumentParser(description='Process some integers.')
    
    6)
  • parser = argparse.ArgumentParser(description='Process some integers.')
    
    7: Phần thông tin trợ giúp
  • parser = argparse.ArgumentParser(description='Process some integers.')
    
    8: Tên của thuộc tính mà sẽ được thêm vào biến được trả về bởi
    parser = argparse.ArgumentParser(description='Process some integers.')
    
    9.
    parser = argparse.ArgumentParser(description='Process some integers.')
    
    8 ở trong ví dụ là
    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)')
    
    1, và bạn có thể thấy thuộc tính này được gọi sau này.
  • 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)')
    
    2: Một hằng giá trị , không được truyền vào từ CLI nhưng vẫn được lưu bên trong để 1 số hàm bên trong sử dụng, nhất là hàm
    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)')
    
    3
  • 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)')
    
    4: Giá trị mặc định trả về nếu không có biến nào được truyền vào từ CLI.

Trong hàm add_argument, có 2 tham số đặc biệt cần lưu ý là

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)')
5 và
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)')
3

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)')
3: Mỗi tham số truyền vào CLI sẽ được lớp
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))
7 đính với 1
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)')
3 , tức là một hành động duy nhất. Tham số này sẽ định nghĩa cách các tham số truyền vào từ CLI được xử lý. Hành động này có nhiều kiểu như sau:

  • >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    0: hành động này sẽ lưu giá trị truyền vào. Đây là hành động mặc định
  • >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    1: hành động này sẽ lưu trữ giá trị được định nghĩa bởi từ khóa
    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)')
    
    2. Như ở ví dụ trên,
    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)')
    
    2 đang truyền vào hàm
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    4. Biến này thường được dùng với các tham số dạng cờ. Ví dụ:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
Namespace(foo=42)
  • >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    5 và
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    6 : đây là dạng đặc biệt của action
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    1, chuyên dùng để lưu các biến
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    8 và
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    9, và đồng thời tạo các giá trị mặc định
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    9 và
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
    8.
  • parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    
    2: Đếm số lần một
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    
    3 xảy ra
  • parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    
    4: Lưu 1
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    
    5, thêm các tham số truyền vào sau vào
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    
    5 đó.

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)')
5: Như đã nói ở trên thì mỗi tham số truyền vào CLI sẽ được lớp
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))
7 đính với 1
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)')
3 Tham số
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)')
5 có thể đính một số lượng các tham số khác nhau với 1
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)')
3. Các giá trị của
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)')
5 như sau:

  • parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    
    3: Tất cả các tham số truyền vào từ CLI được gom lại vào 1
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    
    5
  • parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    
    5: Giống như
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    
    3. Nhưng sẽ trả ra 1 tin nhắn lỗi nếu không có tham số nào được truyền vào. Đây là giá trị được sử dụng ở ví dụ.
  • parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    
    7: Một số nguyên
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    
    7 các tham số truyền vaò từ CLI sẽ được gom vào một
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    
    5.
  • argparse0: Sẽ chỉ có 1 tham số truyền vào từ CLI được xử lý. Nếu không có tham số nào thì giá trị từ tham số
    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)')
    
    4 sẽ được sử dụng.

4.

argparse2

Hàm

parser = argparse.ArgumentParser(description='Process some integers.')
9 biến các tham số được gửi vào từ CLI thành các thuộc tính của 1 object và trả về object đó. Như vậy có thể thấy trong ví dụ ở bên trên, argparse4 sẽ là một object chứa các biến được truyền vào như argparse5 và
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)')
1. Sau đó hàm argparse7 in ra kết quả trả về khi gọi hàm
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)')
1 với biến
parser = argparse.ArgumentParser(description='Process some integers.')
0. Mình xin phép tổng kết lại các bước và phân tích ví dụ trực tiếp như sau.

Bước 1: Tạo 1 parser từ argparse0

Bước 2: Thêm argparse1 với hàm

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)
8.

  • Dòng
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')

Thêm tham số integers, là một

parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
5 của tất cả các số truyền vào từ CLI, kiểu số bắt buộc là số nguyên.

  • Dòng
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

Thêm tham số integers, là một

parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
5 của tất cả các số truyền vào từ CLI, kiểu số bắt buộc là số nguyên.

Thêm tham số

parser = argparse.ArgumentParser(description='Process some integers.')
1, được lưu vào thuộc tính
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)')
1, được dùng để tạo ra 1 hàm trả về tổng của các tham số truyền vào, hoặc nếu không có tham số
parser = argparse.ArgumentParser(description='Process some integers.')
1 được truyền vào sẽ mặc định trả về giá trị lớn nhất.

Bước 3: Các tham số trên được biến đổi thành thuộc tính của một object.

Bước 4: In ra kết quả khi áp dùng hàm argparse7 với list

parser = argparse.ArgumentParser(description='Process some integers.')
0.