Tập tin vượt qua Python làm đối số

Với việc Python là ngôn ngữ lập trình rất phổ biến, cũng như hỗ trợ cho hầu hết các hệ điều hành và nhiều thư viện giúp xử lý đối số dòng lệnh dễ dàng - nó được sử dụng rộng rãi để tạo các công cụ dòng lệnh cho nhiều mục đích. Các công cụ này có thể bao gồm từ các ứng dụng CLI đơn giản đến những ứng dụng phức tạp hơn, chẳng hạn như công cụ awscli của AWS

Các công cụ phức tạp như thế này thường được người dùng kiểm soát thông qua , cho phép người dùng sử dụng các lệnh cụ thể, đặt tùy chọn, v.v. Ví dụ: các tùy chọn này có thể yêu cầu công cụ xuất thông tin bổ sung, đọc dữ liệu từ một nguồn được chỉ định hoặc gửi đầu ra đến một vị trí nhất định

Nói chung, các đối số được chuyển đến các công cụ CLI khác nhau, tùy thuộc vào hệ điều hành của bạn

  • tương tự Unix.
    $ python arguments-program-name.py
    The script has the name arguments-program-name.py
    $ python /home/user/arguments-program-name.py
    The script has the name /home/user/arguments-program-name.py
    
    5 theo sau bởi một chữ cái, chẳng hạn như
    $ python arguments-program-name.py
    The script has the name arguments-program-name.py
    $ python /home/user/arguments-program-name.py
    The script has the name /home/user/arguments-program-name.py
    
    6, hoặc
    $ python arguments-program-name.py
    The script has the name arguments-program-name.py
    $ python /home/user/arguments-program-name.py
    The script has the name /home/user/arguments-program-name.py
    
    7 theo sau bởi một từ, chẳng hạn như
    $ python arguments-program-name.py
    The script has the name arguments-program-name.py
    $ python /home/user/arguments-program-name.py
    The script has the name /home/user/arguments-program-name.py
    
    8
  • các cửa sổ.
    $ python arguments-program-name.py
    The script has the name arguments-program-name.py
    $ python /home/user/arguments-program-name.py
    The script has the name /home/user/arguments-program-name.py
    
    9 theo sau bởi một chữ cái hoặc từ, chẳng hạn như
    $ python arguments-count.py
    The script is called with 0 arguments
    $ python arguments-count.py --help me
    The script is called with 2 arguments
    $ python arguments-count.py --option "long string"
    The script is called with 2 arguments
    
    0

Những cách tiếp cận khác nhau này tồn tại vì lý do lịch sử. Nhiều chương trình trên các hệ thống giống Unix hỗ trợ cả ký hiệu dấu gạch ngang đơn và dấu gạch ngang kép. Ký hiệu gạch ngang đơn chủ yếu được sử dụng với các tùy chọn một chữ cái, trong khi dấu gạch ngang kép thể hiện danh sách tùy chọn dễ đọc hơn, điều này đặc biệt hữu ích cho các tùy chọn phức tạp cần rõ ràng hơn

Ghi chú. Trong bài viết này, chúng ta sẽ chỉ tập trung vào định dạng giống Unix của

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
5 và
$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
7

Hãy nhớ rằng cả tên và ý nghĩa của một đối số đều dành riêng cho một chương trình - không có định nghĩa chung, ngoài một số quy ước phổ biến như

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
8 để biết thêm thông tin về cách sử dụng công cụ. Là nhà phát triển tập lệnh Python, bạn sẽ quyết định cung cấp đối số nào cho người gọi và họ làm gì. Điều này đòi hỏi phải đánh giá đúng

Khi danh sách các đối số khả dụng của bạn tăng lên, mã của bạn sẽ trở nên phức tạp hơn khi cố phân tích chúng một cách chính xác. May mắn thay, trong Python có sẵn một số thư viện giúp bạn việc này. Chúng tôi sẽ đề cập đến một số giải pháp phổ biến nhất, bao gồm từ "tự làm" với

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
4, đến phương pháp "làm cho bạn" với
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
5

Xử lý đối số dòng lệnh với Python

Python 3+ và hệ sinh thái xung quanh hỗ trợ một số cách xử lý đối số dòng lệnh khác nhau. Có nhiều thư viện hỗ trợ phân tích đối số dòng lệnh

Cách tích hợp sẵn là sử dụng mô-đun

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6. Về tên gọi và cách sử dụng, nó liên quan trực tiếp đến thư viện C (
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
7)

Cách thứ hai là mô-đun

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
8, xử lý cả tùy chọn ngắn và dài, bao gồm cả việc đánh giá các giá trị tham số

Mô-đun argparse, được bắt nguồn từ mô-đun

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
9 (có sẵn cho Python 2. 7)

Mô-đun

$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
0, có sẵn trên GitHub, cũng cho phép chức năng tương tự

Gần đây, thư viện

$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
1 cũng đang nổi lên, như một phương tiện để thay thế
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
9 và
$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
3

Mỗi cách trong số này đều có ưu và nhược điểm, vì vậy, đáng để đánh giá từng cách để xem cách nào phù hợp nhất với nhu cầu của bạn

Mô-đun hệ thống

Đây là một mô-đun cơ bản đã được xuất xưởng với Python từ những ngày đầu. Nó có một cách tiếp cận rất giống với thư viện C bằng cách sử dụng

$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
4/
$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
5 để truy cập các đối số. Mô-đun sys thực hiện các đối số dòng lệnh trong một cấu trúc danh sách đơn giản có tên là
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
4

Mỗi phần tử danh sách đại diện cho một đối số duy nhất. Mục đầu tiên trong danh sách,

$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
7, là tên của tập lệnh Python. Phần còn lại của các phần tử danh sách,
$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
8 đến
$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
9, là các đối số dòng lệnh từ 2 đến n

Là một dấu phân cách giữa các đối số, một khoảng trắng được sử dụng. Các giá trị đối số có chứa khoảng trắng trong đó phải được bao quanh bởi dấu ngoặc kép để được phân tích cú pháp chính xác bởi

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6

Tương đương với

$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
4 chỉ là số phần tử trong danh sách. Để có được giá trị này, hãy sử dụng toán tử Python
def validate_name(value):
    return len(value) > 15

flags.register_validator('name',
                         validate_name,
                         message='Name is over 15 characters long.',
                         flag_values=FLAGS)
2. Chúng tôi sẽ hiển thị điều này trong một ví dụ mã sau này

In đối số CLI đầu tiên

Trong ví dụ đầu tiên này, tập lệnh của chúng tôi sẽ xác định cách nó được gọi. Thông tin này được giữ trong đối số dòng lệnh đầu tiên, được lập chỉ mục bằng 0. Đoạn mã dưới đây cho biết cách bạn lấy tên tập lệnh Python của mình

import sys

print("The script has the name %s" % (sys.argv[0])

Lưu mã này vào một tệp có tên

def validate_name(value):
    return len(value) > 15

flags.register_validator('name',
                         validate_name,
                         message='Name is over 15 characters long.',
                         flag_values=FLAGS)
3, sau đó gọi nó như hình bên dưới. Đầu ra như sau và chứa tên tệp, bao gồm đường dẫn đầy đủ của nó

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py

Như bạn có thể thấy từ lệnh gọi thứ hai ở trên, chúng tôi không chỉ nhận được tên của tệp Python mà còn có đường dẫn đầy đủ được sử dụng để gọi nó

Đếm số đối số

Trong ví dụ thứ hai này, chúng ta chỉ cần đếm số lượng đối số dòng lệnh bằng cách sử dụng phương thức

def validate_name(value):
    return len(value) > 15

flags.register_validator('name',
                         validate_name,
                         message='Name is over 15 characters long.',
                         flag_values=FLAGS)
2 tích hợp sẵn.
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
4 là danh sách mà chúng ta phải kiểm tra. Trong đoạn mã dưới đây, chúng tôi lấy số lượng đối số và sau đó trừ đi 1 vì một trong những đối số đó (i. e. cái đầu tiên) luôn được đặt làm tên của tệp, điều này không phải lúc nào cũng hữu ích với chúng tôi. Do đó, số lượng đối số thực tế được người dùng chuyển là
def validate_name(value):
    return len(value) > 15

flags.register_validator('name',
                         validate_name,
                         message='Name is over 15 characters long.',
                         flag_values=FLAGS)
6

Lưu và đặt tên cho tệp này là đối số. py. Một số ví dụ về cách gọi tập lệnh này được hiển thị bên dưới. Điều này bao gồm ba kịch bản khác nhau

  • Một cuộc gọi mà không có bất kỳ đối số dòng lệnh nào nữa
  • Một cuộc gọi với hai đối số
  • Một cuộc gọi có hai đối số, trong đó đối số thứ hai là một chuỗi được trích dẫn có chứa khoảng trắng
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
Lặp lại thông qua các đối số

Ví dụ thứ ba của chúng tôi xuất ra mọi đối số được gửi tới tập lệnh Python, ngoại trừ chính tên chương trình. Do đó, chúng tôi lặp qua các đối số dòng lệnh bắt đầu bằng phần tử danh sách thứ hai. Nhớ lại rằng đây là chỉ mục 1 vì các danh sách dựa trên 0 trong Python

Dưới đây, chúng tôi gọi mã của mình, mã này đã được lưu vào tệp đối số-đầu ra. py. Như đã thực hiện với ví dụ trước của chúng tôi, đầu ra minh họa ba cuộc gọi khác nhau

  • Một cuộc gọi mà không có bất kỳ đối số
  • Một cuộc gọi với hai đối số
  • Một cuộc gọi có hai đối số, trong đó đối số thứ hai là một chuỗi được trích dẫn chứa khoảng trắng
$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string

Hãy nhớ rằng, điểm hiển thị ví dụ về chuỗi được trích dẫn là các tham số thường được phân tách bằng dấu cách, trừ khi chúng được bao quanh bởi dấu ngoặc kép

Cờ Abseil (
$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
1)

Thư viện Flags của Abseil có nghĩa là đưa các đối số dòng lệnh vào sản xuất, với các đối số dòng lệnh phân tán. Khi một mô-đun sử dụng các cờ dòng lệnh và được nhập vào một mô-đun khác - mô-đun kia cũng nhập các cờ đó và có thể xử lý chúng bằng cách chuyển tiếp chúng đến mô-đun đã nhập

Điều này làm cho các đối số dòng lệnh phức tạp được chia sẻ giữa các mô-đun trở nên dễ dàng hơn và ít dài dòng hơn

Ngoài ra, thư viện cho phép bạn xác định các giá trị mặc định, mô tả và kiểu dữ liệu của các đối số, vì vậy không cần kiểm tra và chuyển đổi bổ sung

Các loại dữ liệu được hỗ trợ là

  • def validate_name(value):
        return len(value) > 15
    
    flags.register_validator('name',
                             validate_name,
                             message='Name is over 15 characters long.',
                             flag_values=FLAGS)
    
    8
  • def validate_name(value):
        return len(value) > 15
    
    flags.register_validator('name',
                             validate_name,
                             message='Name is over 15 characters long.',
                             flag_values=FLAGS)
    
    9
  • from absl import flags
    import sys
    
    flags.DEFINE_string('name', 'User', 'The name of the user.')
    flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)
    
    FLAGS = flags.FLAGS
    FLAGS(sys.argv)
    
    print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
    
    0
  • from absl import flags
    import sys
    
    flags.DEFINE_string('name', 'User', 'The name of the user.')
    flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)
    
    FLAGS = flags.FLAGS
    FLAGS(sys.argv)
    
    print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
    
    1
  • from absl import flags
    import sys
    
    flags.DEFINE_string('name', 'User', 'The name of the user.')
    flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)
    
    FLAGS = flags.FLAGS
    FLAGS(sys.argv)
    
    print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
    
    2
  • from absl import flags
    import sys
    
    flags.DEFINE_string('name', 'User', 'The name of the user.')
    flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)
    
    FLAGS = flags.FLAGS
    FLAGS(sys.argv)
    
    print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
    
    3

Cũng như

from absl import flags
import sys

flags.DEFINE_string('name', 'User', 'The name of the user.')
flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)

FLAGS = flags.FLAGS
FLAGS(sys.argv)

print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
4,
from absl import flags
import sys

flags.DEFINE_string('name', 'User', 'The name of the user.')
flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)

FLAGS = flags.FLAGS
FLAGS(sys.argv)

print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
5 và
from absl import flags
import sys

flags.DEFINE_string('name', 'User', 'The name of the user.')
flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)

FLAGS = flags.FLAGS
FLAGS(sys.argv)

print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
6 cho đầu vào đa đối số. Ngoài ra, chạy
$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
8,
from absl import flags
import sys

flags.DEFINE_string('name', 'User', 'The name of the user.')
flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)

FLAGS = flags.FLAGS
FLAGS(sys.argv)

print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
8, v.v. in các cờ hiện có và mô tả của chúng, ở các định dạng khác nhau

Hãy xem hướng dẫn thực hành, thực tế của chúng tôi để học Git, với các phương pháp hay nhất, tiêu chuẩn được ngành chấp nhận và bao gồm bảng gian lận. Dừng các lệnh Git trên Google và thực sự tìm hiểu nó

Thư viện cũng cho phép bạn xác định xác thực - cả về phạm vi, chẳng hạn như giá trị dựa trên số nguyên có

from absl import flags
import sys

flags.DEFINE_string('name', 'User', 'The name of the user.')
flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)

FLAGS = flags.FLAGS
FLAGS(sys.argv)

print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
9 hoặc
$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
0 được chấp nhận và chạy các phương thức tùy ý để kiểm tra giá trị

def validate_name(value):
    return len(value) > 15

flags.register_validator('name',
                         validate_name,
                         message='Name is over 15 characters long.',
                         flag_values=FLAGS)

Thu thập những điều này thành một ví dụ cụ thể

from absl import flags
import sys

flags.DEFINE_string('name', 'User', 'The name of the user.')
flags.DEFINE_integer('tasks', 0, 'The number of tasks a user has.', lower_bound=0)

FLAGS = flags.FLAGS
FLAGS(sys.argv)

print(f"{FLAGS.name} has {FLAGS.tasks} tasks to work on.")
$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
$ python flags.py --name=John --tasks=-1

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
    return self.parser.parse(argument)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
    raise ValueError('%s is not %s' % (val, self.syntactic_help))
ValueError: -1 is not a non-negative integer
...

Mô-đun argparse

Mô-đun argparse đã có sẵn từ Python 3. 2 và cải tiến của mô-đun

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
9 tồn tại cho đến Python 2. 7. Tài liệu Python chứa mô tả API và hướng dẫn chi tiết về tất cả các phương pháp

Mô-đun cung cấp giao diện dòng lệnh với đầu ra được tiêu chuẩn hóa, trong khi hai giải pháp trước để lại phần lớn công việc cho bạn.

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
5 cho phép xác minh các đối số cố định và tùy chọn, với việc kiểm tra tên theo kiểu ngắn hoặc dài. Là một đối số tùy chọn mặc định, nó bao gồm
$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
6, cùng với phiên bản dài của nó là
$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
8. Đối số này được kèm theo một thông báo trợ giúp mặc định mô tả các đối số được chấp nhận

Mã bên dưới hiển thị quá trình khởi tạo trình phân tích cú pháp và đầu ra bên dưới hiển thị lệnh gọi cơ bản, theo sau là thông báo trợ giúp. Trái ngược với các lệnh gọi Python mà chúng tôi đã sử dụng trong các ví dụ trước, hãy nhớ sử dụng Python 3 với các ví dụ này

$ python3 arguments-argparse-basic.py 
$ python3 arguments-argparse-basic.py -h
usage: arguments-argparse-basic.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 arguments-argparse-basic.py --verbose
usage: arguments-argparse-basic.py [-h]
arguments-argparse-basic.py: error: unrecognized arguments: --verbose

Trong bước tiếp theo, chúng tôi sẽ thêm mô tả tùy chỉnh vào thông báo trợ giúp cho người dùng của chúng tôi. Khởi tạo trình phân tích cú pháp theo cách này cho phép một văn bản bổ sung. Đoạn mã bên dưới lưu trữ mô tả trong biến

$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
5, được cung cấp rõ ràng cho lớp
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
5 dưới dạng tham số
$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
7. Gọi mã này bên dưới, bạn có thể thấy đầu ra trông như thế nào

$ python3 arguments-argparse-description.py --help
usage: arguments-argparse-description.py [-h]

This is a test program. It demonstrates how to use the argparse module with a
program description.

optional arguments:
  -h, --help  show this help message and exit

Ở bước cuối cùng, chúng tôi sẽ thêm một đối số tùy chọn có tên là

$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
8, có một đối số kiểu dài tương ứng có tên là
$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
9. Để làm như vậy, chúng tôi sử dụng phương pháp
$ python flags.py --name=John --tasks=-1

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
    return self.parser.parse(argument)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
    raise ValueError('%s is not %s' % (val, self.syntactic_help))
ValueError: -1 is not a non-negative integer
...
0 mà chúng tôi gọi với ba tham số (chỉ hiển thị cho
$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
9)

  • Tên của thông số.
    $ python flags.py --name=John --tasks=5
    John has 5 tasks to work on.
    
    9
  • Văn bản trợ giúp cho tham số.
    $ python flags.py --name=John --tasks=-1
    
    Traceback (most recent call last):
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
        return self.parser.parse(argument)
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
        raise ValueError('%s is not %s' % (val, self.syntactic_help))
    ValueError: -1 is not a non-negative integer
    ...
    
    3
  • Hành động (không có giá trị bổ sung).
    $ python flags.py --name=John --tasks=-1
    
    Traceback (most recent call last):
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
        return self.parser.parse(argument)
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
        raise ValueError('%s is not %s' % (val, self.syntactic_help))
    ValueError: -1 is not a non-negative integer
    ...
    
    4

Mã nguồn cho điều đó được hiển thị ở bên dưới. Việc đọc các đối số vào biến có tên là

$ python flags.py --name=John --tasks=-1

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
    return self.parser.parse(argument)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
    raise ValueError('%s is not %s' % (val, self.syntactic_help))
ValueError: -1 is not a non-negative integer
...
5 được thực hiện thông qua phương thức
$ python flags.py --name=John --tasks=-1

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
    return self.parser.parse(argument)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
    raise ValueError('%s is not %s' % (val, self.syntactic_help))
ValueError: -1 is not a non-negative integer
...
6 từ đối tượng
$ python flags.py --name=John --tasks=-1

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
    return self.parser.parse(argument)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
    raise ValueError('%s is not %s' % (val, self.syntactic_help))
ValueError: -1 is not a non-negative integer
...
7. Lưu ý rằng bạn gửi cả phiên bản ngắn và dài trong một cuộc gọi. Cuối cùng, bạn kiểm tra xem các thuộc tính
$ python flags.py --name=John --tasks=-1

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
    return self.parser.parse(argument)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
    raise ValueError('%s is not %s' % (val, self.syntactic_help))
ValueError: -1 is not a non-negative integer
...
8 hoặc
$ python flags.py --name=John --tasks=-1

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_flag.py", line 180, in _parse
    return self.parser.parse(argument)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/absl/flags/_argument_parser.py", line 168, in parse
    raise ValueError('%s is not %s' % (val, self.syntactic_help))
ValueError: -1 is not a non-negative integer
...
9 đã được đặt chưa và xuất ra thông báo phiên bản

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
0

Đối số

$ python flags.py --name=John --tasks=5
John has 5 tasks to work on.
9 không yêu cầu cung cấp giá trị trên dòng lệnh. Đó là lý do tại sao chúng tôi đặt đối số hành động thành
$ python3 arguments-argparse-basic.py 
$ python3 arguments-argparse-basic.py -h
usage: arguments-argparse-basic.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 arguments-argparse-basic.py --verbose
usage: arguments-argparse-basic.py [-h]
arguments-argparse-basic.py: error: unrecognized arguments: --verbose
1. Trong các trường hợp khác, bạn có thể cần một giá trị được chỉ định bổ sung, chẳng hạn nếu bạn chỉ định một thể tích, chiều cao hoặc chiều rộng nhất định. Điều này được thể hiện trong ví dụ tiếp theo. Là trường hợp mặc định, xin lưu ý rằng tất cả các đối số được hiểu là chuỗi

Ở đây chúng tôi chỉ ra điều gì sẽ xảy ra khi gửi các giá trị đối số khác nhau. Điều này bao gồm cả phiên bản ngắn và dài, cũng như thông báo trợ giúp

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
1

Mô-đun getopt

Như bạn có thể nhận thấy trước đây, mô-đun

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6 chỉ chia chuỗi dòng lệnh thành các khía cạnh đơn lẻ. Mô-đun getopt của Python đi xa hơn một chút và mở rộng việc phân tách chuỗi đầu vào bằng cách xác thực tham số. Dựa trên hàm
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
8 C, nó cho phép cả tùy chọn ngắn và dài, bao gồm cả việc gán giá trị

Trong thực tế, nó yêu cầu mô-đun

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6 xử lý dữ liệu đầu vào đúng cách. Để làm như vậy, cả mô-đun
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6 và mô-đun
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
8 phải được tải trước. Tiếp theo, từ danh sách các tham số đầu vào, chúng tôi xóa phần tử danh sách đầu tiên (xem mã bên dưới) và lưu trữ danh sách đối số dòng lệnh còn lại trong biến có tên
$ python3 arguments-argparse-basic.py 
$ python3 arguments-argparse-basic.py -h
usage: arguments-argparse-basic.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 arguments-argparse-basic.py --verbose
usage: arguments-argparse-basic.py [-h]
arguments-argparse-basic.py: error: unrecognized arguments: --verbose
7

Các đối số trong

$ python3 arguments-argparse-basic.py 
$ python3 arguments-argparse-basic.py -h
usage: arguments-argparse-basic.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 arguments-argparse-basic.py --verbose
usage: arguments-argparse-basic.py [-h]
arguments-argparse-basic.py: error: unrecognized arguments: --verbose
7 hiện có thể được phân tích cú pháp bằng phương pháp
$ python3 arguments-argparse-basic.py 
$ python3 arguments-argparse-basic.py -h
usage: arguments-argparse-basic.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 arguments-argparse-basic.py --verbose
usage: arguments-argparse-basic.py [-h]
arguments-argparse-basic.py: error: unrecognized arguments: --verbose
9. Nhưng trước khi làm điều đó, chúng ta cần cho
$ python3 arguments-argparse-basic.py 
$ python3 arguments-argparse-basic.py -h
usage: arguments-argparse-basic.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 arguments-argparse-basic.py --verbose
usage: arguments-argparse-basic.py [-h]
arguments-argparse-basic.py: error: unrecognized arguments: --verbose
9 biết thông số nào hợp lệ. Chúng được định nghĩa như thế này

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
2

Điều này có nghĩa là những đối số này là những đối số mà chúng tôi coi là hợp lệ, cùng với một số thông tin bổ sung

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
3

Bạn có thể nhận thấy rằng tùy chọn rút gọn

$ python3 arguments-argparse-description.py --help
usage: arguments-argparse-description.py [-h]

This is a test program. It demonstrates how to use the argparse module with a
program description.

optional arguments:
  -h, --help  show this help message and exit
1 được tiếp tục bằng dấu hai chấm,
$ python3 arguments-argparse-description.py --help
usage: arguments-argparse-description.py [-h]

This is a test program. It demonstrates how to use the argparse module with a
program description.

optional arguments:
  -h, --help  show this help message and exit
2. Điều này nói với
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
8 rằng tùy chọn này sẽ được gán một giá trị

Điều này bây giờ cho phép chúng tôi xử lý một danh sách các đối số. Phương thức

$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
3 yêu cầu ba tham số được định cấu hình - danh sách các đối số thực tế từ
$ python arguments-output.py
$ python arguments-output.py --help me
Parameter 1: --help
Parameter 2: me
$ python arguments-output.py --option "long string"
Parameter 1: --option
Parameter 2: long string
5, cũng như cả các tùy chọn ngắn và dài hợp lệ (hiển thị trong đoạn mã trước)

Bản thân cuộc gọi phương thức được giữ trong câu lệnh thử bắt để che lỗi trong quá trình đánh giá. Một ngoại lệ được đưa ra nếu một đối số được phát hiện không phải là một phần của danh sách như đã xác định trước đó. Tập lệnh Python sẽ in thông báo lỗi ra màn hình và thoát với mã lỗi 2

Cuối cùng, các đối số có giá trị tương ứng được lưu trữ trong hai biến tên là

$ python3 arguments-argparse-description.py --help
usage: arguments-argparse-description.py [-h]

This is a test program. It demonstrates how to use the argparse module with a
program description.

optional arguments:
  -h, --help  show this help message and exit
6 và
$ python3 arguments-argparse-description.py --help
usage: arguments-argparse-description.py [-h]

This is a test program. It demonstrates how to use the argparse module with a
program description.

optional arguments:
  -h, --help  show this help message and exit
7. Giờ đây, bạn có thể dễ dàng đánh giá các biến này trong mã của mình. Chúng ta có thể sử dụng vòng lặp
$ python3 arguments-argparse-description.py --help
usage: arguments-argparse-description.py [-h]

This is a test program. It demonstrates how to use the argparse module with a
program description.

optional arguments:
  -h, --help  show this help message and exit
8 để lặp qua danh sách các đối số được nhận diện, mục này nối tiếp mục khác

Dưới đây bạn có thể thấy đầu ra từ việc thực thi mã này. Chúng tôi sẽ chỉ ra cách chương trình phản ứng với cả đối số chương trình hợp lệ và không hợp lệ

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
4

Cuộc gọi cuối cùng đến chương trình của chúng tôi lúc đầu có vẻ hơi khó hiểu. Để hiểu nó, bạn cần biết rằng các tùy chọn tốc ký (đôi khi còn được gọi là cờ) có thể được sử dụng cùng với một dấu gạch ngang. Điều này cho phép công cụ của bạn dễ dàng chấp nhận nhiều tùy chọn hơn. Ví dụ: gọi

$ python3 arguments-argparse-description.py --help
usage: arguments-argparse-description.py [-h]

This is a test program. It demonstrates how to use the argparse module with a
program description.

optional arguments:
  -h, --help  show this help message and exit
9 cũng giống như gọi
$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
00. Vì vậy, trong cuộc gọi cuối cùng ở trên, mô-đun
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
8 nghĩ rằng người dùng đang cố chuyển
$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
02 dưới dạng tùy chọn, điều này không hợp lệ

Phần kết luận

Trong bài viết này, chúng tôi đã chỉ ra nhiều phương pháp khác nhau để truy xuất đối số dòng lệnh trong Python, bao gồm sử dụng

$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6,
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
8 và
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
5. Các mô-đun này khác nhau về chức năng, một số cung cấp nhiều hơn những mô-đun khác.
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6 hoàn toàn linh hoạt, trong khi cả
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
8và
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
5 đều yêu cầu một số cấu trúc. Ngược lại, chúng bao gồm hầu hết các công việc phức tạp mà
$ python arguments-count.py
The script is called with 0 arguments
$ python arguments-count.py --help me
The script is called with 2 arguments
$ python arguments-count.py --option "long string"
The script is called with 2 arguments
6 giao cho bạn. Sau khi xem qua các ví dụ được cung cấp, bạn sẽ có thể xác định mô-đun nào phù hợp nhất với dự án của mình

Trong bài viết này chúng ta không nói đến các giải pháp khác như module

$ python arguments-program-name.py
The script has the name arguments-program-name.py
$ python /home/user/arguments-program-name.py
The script has the name /home/user/arguments-program-name.py
10, chúng ta chỉ đề cập đến nó. Mô-đun này tuân theo một cách tiếp cận hoàn toàn khác và sẽ được giải thích chi tiết trong một trong các bài viết tiếp theo