Trang này chứa thông tin tham chiếu API. Để có phần giới thiệu nhẹ nhàng hơn về phân tích cú pháp dòng lệnh Python, hãy xem
Mô-đun giúp dễ dàng viết các giao diện dòng lệnh thân thiện với người dùng. Chương trình xác định những đối số mà nó yêu cầu và sẽ tìm ra cách phân tích những đối số đó ra khỏi. Mô-đun cũng tự động tạo thông báo trợ giúp và sử dụng. Mô-đun cũng sẽ báo lỗi khi người dùng cung cấp cho chương trình các đối số không hợp lệ
Chức năng cốt lõi
Hỗ trợ của mô-đun cho các giao diện dòng lệnh được xây dựng xung quanh một phiên bản của. Nó là nơi chứa các thông số kỹ thuật đối số và có các tùy chọn áp dụng toàn bộ trình phân tích cú pháp
parser = argparse.ArgumentParser[ prog = 'ProgramName', description = 'What the program does', epilog = 'Text at the bottom of help']
Phương thức đính kèm các thông số kỹ thuật đối số riêng lẻ vào trình phân tích cú pháp. Nó hỗ trợ các đối số vị trí, các tùy chọn chấp nhận giá trị và cờ bật/tắt
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
Phương thức chạy trình phân tích cú pháp và đặt dữ liệu được trích xuất vào một đối tượng
args = parser.parse_args[] print[args.filename, args.count, args.verbose]
Liên kết nhanh cho add_argument[]
Tên
Sự miêu tả
giá trị
Chỉ định cách xử lý một đối số
_______1_______11, _______1_______12, _______1_______13, _______1_______14, _______1_______15, _______1_______16, _______1_______17, _______1_______18
Giới hạn các giá trị cho một tập hợp các lựa chọn cụ thể
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag19,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag20, hoặc trường hợp
Lưu trữ một giá trị không đổi
Giá trị mặc định được sử dụng khi không cung cấp đối số
Mặc định là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22
Chỉ định tên thuộc tính được sử dụng trong không gian tên kết quả
Thông báo trợ giúp cho một đối số
Tên hiển thị thay thế cho đối số như được hiển thị trong phần trợ giúp
Số lần đối số có thể được sử dụng
,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag24,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag25,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag26, hoặc
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag27
Cho biết đối số là bắt buộc hay tùy chọn
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag28 hoặc
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29
Tự động chuyển đổi một đối số thành loại đã cho
, ,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag32 hoặc chức năng có thể gọi được
Thí dụ
Đoạn mã sau là một chương trình Python lấy danh sách các số nguyên và tạo ra tổng hoặc giá trị lớn nhấ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]]
Giả sử mã Python ở trên được lưu vào một tệp có tên là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag33, nó có thể chạy ở dòng lệnh và nó cung cấp các thông báo trợ giúp hữu ích
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
Khi chạy với các đối số thích hợp, nó sẽ in tổng hoặc giá trị lớn nhất của các số nguyên dòng lệnh
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
Nếu đối số không hợp lệ được truyền vào, một lỗi sẽ được hiển thị
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'
Các phần sau đây hướng dẫn bạn qua ví dụ này
Tạo trình phân tích cú pháp
Bước đầu tiên trong việc sử dụng là tạo một đối tượng
>>> parser = argparse.ArgumentParser[description='Process some integers.']
Đối tượng sẽ chứa tất cả thông tin cần thiết để phân tích dòng lệnh thành các kiểu dữ liệu Python
Thêm đối số
Việc điền thông tin về các đối số của chương trình được thực hiện bằng cách gọi phương thức. Nói chung, các cuộc gọi này cho biết cách lấy các chuỗi trên dòng lệnh và biến chúng thành các đối tượng. Thông tin này được lưu trữ và sử dụng khi được gọi. Ví dụ
>>> 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]']
Sau đó, việc gọi sẽ trả về một đối tượng có hai thuộc tính,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag42 và
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag43. Thuộc tính
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag42 sẽ là danh sách gồm một hoặc nhiều số nguyên và thuộc tính
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag43 sẽ là hàm, nếu
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag47 được chỉ định tại dòng lệnh hoặc hàm nếu nó không được chỉ định
Phân tích đối số
phân tích các đối số thông qua phương thức. Điều này sẽ kiểm tra dòng lệnh, chuyển đổi từng đối số thành loại thích hợp và sau đó gọi hành động thích hợp. Trong hầu hết các trường hợp, điều này có nghĩa là một đối tượng đơn giản sẽ được xây dựng từ các thuộc tính được phân tích cú pháp từ dòng lệnh
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]
Trong một tập lệnh, thường sẽ được gọi mà không có đối số và sẽ tự động xác định các đối số dòng lệnh từ
Đối tượng ArgumentParser
lớp argparse. Trình phân tích đối số[prog=Không có . HelpFormatter, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter , prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True]Tạo một đối tượng mới. Tất cả các tham số phải được chuyển thành đối số từ khóa. Mỗi tham số có mô tả chi tiết hơn bên dưới, nhưng tóm lại chúng là
- Tên chương trình [mặc định.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
56]- Chuỗi mô tả cách sử dụng chương trình [mặc định. được tạo từ các đối số được thêm vào trình phân tích cú pháp]
- Văn bản hiển thị trước trợ giúp đối số [theo mặc định, không có văn bản]
- Văn bản để hiển thị sau đối số trợ giúp [theo mặc định, không có văn bản]
- Một danh sách các đối tượng có đối số cũng nên được đưa vào
- Một lớp để tùy chỉnh đầu ra trợ giúp
- Tập hợp các ký tự tiền tố đối số tùy chọn [mặc định. ‘-‘]
- Tập hợp các ký tự tiền tố tệp mà từ đó các đối số bổ sung sẽ được đọc [mặc định.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22]- Giá trị mặc định chung cho các đối số [mặc định.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22]- Chiến lược giải quyết các tùy chọn xung đột [thường không cần thiết]
- Add a
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
60 option to the parser [default.parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28]- Allows long options to be abbreviated if the abbreviation is unambiguous. [default.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28]- Determines whether or not ArgumentParser exits with error info when an error occurs. [default.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28]
Changed in version 3. 5. allow_abbrev parameter was added.
Changed in version 3. 8. In previous versions, allow_abbrev also disabled grouping of short flags such as
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag64 to mean
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag65.
Changed in version 3. 9. exit_on_error parameter was added.
The following sections describe how each of these are used
prog
By default, objects use
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag67 to determine how to display the name of the program in help messages. This default is almost always desirable because it will make the help messages match how the program was invoked on the command line. For example, consider a file named
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag68 with the following code
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag0
The help for this program will display
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag68 as the program name [regardless of where the program was invoked from]
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag1
To change this default behavior, another value can be supplied using the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag70 argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag2
Note that the program name, whether determined from
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag67 or from the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag70 argument, is available to help messages using the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag74 format specifier
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag3
usage
By default, calculates the usage message from the arguments it contains
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag4
The default message can be overridden with the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag76 keyword argument
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag5
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag74 format specifier is available to fill in the program name in your usage messages
description
Most calls to the constructor will use the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag79 keyword argument. This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag6
By default, the description will be line-wrapped so that it fits within the given space. To change this behavior, see the argument
epilog
Some programs like to display additional description of the program after the description of the arguments. Such text can be specified using the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag80 argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag7
As with the argument, the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag80 text is by default line-wrapped, but this behavior can be adjusted with the argument to
parents
Sometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag84 argument to can be used. The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag84 argument takes a list of objects, collects all the positional and optional actions from them, and adds these actions to the object being constructed
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag8
Lưu ý rằng hầu hết các trình phân tích cú pháp gốc sẽ chỉ định
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag89. Nếu không, sẽ thấy hai tùy chọn
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag60 [một ở cha và một ở con] và đưa ra lỗi
Ghi chú
Bạn phải khởi tạo đầy đủ các trình phân tích cú pháp trước khi chuyển chúng qua
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag84. Nếu bạn thay đổi trình phân tích cú pháp gốc sau trình phân tích cú pháp con, những thay đổi đó sẽ không được phản ánh trong trình phân tích cú pháp con
định dạng_class
các đối tượng cho phép tùy chỉnh định dạng trợ giúp bằng cách chỉ định một lớp định dạng thay thế. Hiện tại, có bốn lớp như vậy
lớp argparse. RawDescriptionHelpFormatterlớp argparse. RawTextHelpFormatterlớp argparse. ArgumentDefaultsHelpFormatterlớp argparse. MetavarTypeHelpFormattervà cung cấp nhiều quyền kiểm soát hơn đối với cách hiển thị các mô tả bằng văn bản. Theo mặc định, các đối tượng ngắt dòng và văn bản trong thông báo trợ giúp dòng lệnh
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag9
Chuyển dưới dạng
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag98 cho biết rằng và đã được định dạng chính xác và không được ngắt dòng
args = parser.parse_args[] print[args.filename, args.count, args.verbose]0
duy trì khoảng trắng cho tất cả các loại văn bản trợ giúp, bao gồm cả mô tả đối số. Tuy nhiên, nhiều dòng mới được thay thế bằng một. Nếu bạn muốn giữ nguyên nhiều dòng trống, hãy thêm khoảng cách giữa các dòng mới
tự động thêm thông tin về các giá trị mặc định vào từng thông báo trợ giúp đối số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]1
sử dụng tên của đối số cho mỗi đối số làm tên hiển thị cho các giá trị của nó [thay vì sử dụng như trình định dạng thông thường thực hiện]
args = parser.parse_args[] print[args.filename, args.count, args.verbose]2
tiền tố_chars
Hầu hết các tùy chọn dòng lệnh sẽ sử dụng
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 làm tiền tố, e. g.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]03. Trình phân tích cú pháp cần hỗ trợ các ký tự tiền tố khác hoặc bổ sung, e. g. for options like
args = parser.parse_args[] print[args.filename, args.count, args.verbose]04 or
args = parser.parse_args[] print[args.filename, args.count, args.verbose]05, may specify them using the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]06 argument to the ArgumentParser constructor
args = parser.parse_args[] print[args.filename, args.count, args.verbose]3
Đối số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]06 mặc định là
args = parser.parse_args[] print[args.filename, args.count, args.verbose]08. Việc cung cấp một bộ ký tự không bao gồm
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 sẽ khiến các tùy chọn
args = parser.parse_args[] print[args.filename, args.count, args.verbose]03 không được phép
fromfile_prefix_chars
Đôi khi, khi xử lý một danh sách đối số đặc biệt dài, có thể nên giữ danh sách đối số trong một tệp thay vì gõ nó ra ở dòng lệnh. Nếu đối số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]11 được cung cấp cho hàm tạo, thì các đối số bắt đầu bằng bất kỳ ký tự nào được chỉ định sẽ được coi là tệp và sẽ được thay thế bằng các đối số mà chúng chứa. Ví dụ
args = parser.parse_args[] print[args.filename, args.count, args.verbose]4
Các đối số được đọc từ một tệp theo mặc định phải là một đối số trên mỗi dòng [nhưng cũng xem ] và được xử lý như thể chúng ở cùng một vị trí với đối số tham chiếu tệp gốc trên dòng lệnh. Vì vậy, trong ví dụ trên, biểu thức
args = parser.parse_args[] print[args.filename, args.count, args.verbose]14 được coi là tương đương với biểu thức
args = parser.parse_args[] print[args.filename, args.count, args.verbose]15
Đối số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]11 mặc định là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22, nghĩa là các đối số sẽ không bao giờ được coi là tham chiếu tệp
đối số_default
Nói chung, giá trị mặc định của đối số được chỉ định bằng cách chuyển giá trị mặc định cho hoặc bằng cách gọi các phương thức với một tập hợp cụ thể các cặp tên-giá trị. Tuy nhiên, đôi khi, có thể hữu ích khi chỉ định một mặc định trên toàn bộ trình phân tích cú pháp cho các đối số. Điều này có thể được thực hiện bằng cách chuyển đối số từ khóa
args = parser.parse_args[] print[args.filename, args.count, args.verbose]20 tới. Ví dụ: để ngăn chặn toàn bộ việc tạo thuộc tính trong các cuộc gọi, chúng tôi cung cấp ____2_______23
args = parser.parse_args[] print[args.filename, args.count, args.verbose]5
allow_abbrev
Thông thường, khi bạn chuyển một danh sách đối số sang phương thức của một tùy chọn dài
Có thể tắt tính năng này bằng cách cài đặt
args = parser.parse_args[] print[args.filename, args.count, args.verbose]26 thành
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29
args = parser.parse_args[] print[args.filename, args.count, args.verbose]6
Mới trong phiên bản 3. 5
xung đột_handler
các đối tượng không cho phép hai hành động với cùng một chuỗi tùy chọn. Theo mặc định, các đối tượng đưa ra một ngoại lệ nếu một nỗ lực được thực hiện để tạo một đối số với một chuỗi tùy chọn đã được sử dụng
args = parser.parse_args[] print[args.filename, args.count, args.verbose]7
Đôi khi [đ. g. khi sử dụng ], có thể hữu ích khi ghi đè bất kỳ đối số cũ hơn nào bằng cùng một chuỗi tùy chọn. Để có được hành vi này, giá trị
args = parser.parse_args[] print[args.filename, args.count, args.verbose]30 có thể được cung cấp cho đối số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]31 của
args = parser.parse_args[] print[args.filename, args.count, args.verbose]8
Lưu ý rằng các đối tượng chỉ xóa một hành động nếu tất cả các chuỗi tùy chọn của nó bị ghi đè. Vì vậy, trong ví dụ trên, tác vụ
args = parser.parse_args[] print[args.filename, args.count, args.verbose]03 cũ được giữ lại dưới dạng tác vụ
args = parser.parse_args[] print[args.filename, args.count, args.verbose]35, bởi vì chỉ có chuỗi tùy chọn
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36 bị ghi đè
add_help
Theo mặc định, các đối tượng ArgumentParser thêm một tùy chọn chỉ hiển thị thông báo trợ giúp của trình phân tích cú pháp. Ví dụ: xem xét một tệp có tên
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag68 chứa đoạn mã sau
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag0
Nếu
args = parser.parse_args[] print[args.filename, args.count, args.verbose]38 hoặc
args = parser.parse_args[] print[args.filename, args.count, args.verbose]39 được cung cấp tại dòng lệnh, trợ giúp ArgumentParser sẽ được in
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]]0
Đôi khi, có thể hữu ích khi vô hiệu hóa việc bổ sung tùy chọn trợ giúp này. Điều này có thể đạt được bằng cách chuyển
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29 làm đối số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]41 cho
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
Tùy chọn trợ giúp thường là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag60. Ngoại lệ đối với điều này là nếu
args = parser.parse_args[] print[args.filename, args.count, args.verbose]06 được chỉ định và không bao gồm
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02, trong trường hợp đó,
args = parser.parse_args[] print[args.filename, args.count, args.verbose]38 và
args = parser.parse_args[] print[args.filename, args.count, args.verbose]39 không phải là các lựa chọn hợp lệ. Trong trường hợp này, ký tự đầu tiên trong
args = parser.parse_args[] print[args.filename, args.count, args.verbose]48 được sử dụng làm tiền tố cho các tùy chọn trợ giú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]]2
exit_on_error
Thông thường, khi bạn chuyển một danh sách đối số không hợp lệ sang phương thức của một , nó sẽ thoát với thông tin lỗi
Nếu người dùng muốn bắt lỗi theo cách thủ công, tính năng này có thể được bật bằng cách đặt
args = parser.parse_args[] print[args.filename, args.count, args.verbose]51 thành
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29
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
Mới trong phiên bản 3. 9
Phương thức add_argument[]
Trình phân tích đối số. add_argument[tên hoặc cờ. [ , hành động][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]]Xác định cách phân tích cú pháp một đối số dòng lệnh. Mỗi tham số có mô tả chi tiết hơn bên dưới, nhưng tóm lại chúng là
- Tên hoặc danh sách các chuỗi tùy chọn, e. g.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]
53 hoặcargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
54- The basic type of action to be taken when this argument is encountered at the command line
- Số lượng đối số dòng lệnh nên được sử dụng
- Một giá trị không đổi theo yêu cầu của một số và lựa chọn
- Giá trị được tạo nếu đối số không có trong dòng lệnh và nếu nó không có trong đối tượng không gian tên
- Loại mà đối số dòng lệnh sẽ được chuyển đổi
- Một chuỗi các giá trị được phép cho đối số
- Có thể bỏ qua tùy chọn dòng lệnh hay không [chỉ tùy chọn]
- Một mô tả ngắn gọn về những gì lập luận làm
- Tên cho đối số trong thông báo sử dụng
- Tên của thuộc tính sẽ được thêm vào đối tượng được trả về bởi
The following sections describe how each of these are used
tên hoặc cờ
Phương thức phải biết liệu một đối số tùy chọn, như
args = parser.parse_args[] print[args.filename, args.count, args.verbose]35 hoặc
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36, hoặc một đối số vị trí, như danh sách tên tệp, có được mong đợi hay không. Do đó, các đối số đầu tiên được chuyển đến phải là một chuỗi các cờ hoặc một tên đối số đơn giản
Ví dụ: một đối số tùy chọn có thể được tạo như
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
trong khi một đối số vị trí có thể được tạo ra như
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]]5
Khi được gọi, các đối số tùy chọn sẽ được xác định bằng tiền tố
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 và các đối số còn lại sẽ được coi là vị trí
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
hoạt động
các đối tượng liên kết các đối số dòng lệnh với các hành động. Những hành động này có thể thực hiện bất cứ điều gì với các đối số dòng lệnh được liên kết với chúng, mặc dù hầu hết các hành động chỉ cần thêm một thuộc tính vào đối tượng được trả về bởi. Đối số từ khóa
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64 chỉ định cách xử lý các đối số dòng lệnh. Các hành động được cung cấp là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
11 - Điều này chỉ lưu trữ giá trị của đối số. Đây là hành động mặc định. Ví dụ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]]
7parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
12 - Điều này lưu trữ giá trị được chỉ định bởi đối số từ khóa; . Hành độngparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
12 được sử dụng phổ biến nhất với các đối số tùy chọn chỉ định một số loại cờ. Ví dụ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]]
8parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
13 vàargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
70 - Đây là những trường hợp đặc biệt củaparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
12 được sử dụng để lưu trữ các giá trị tương ứng làparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28 vàparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
29. Ngoài ra, chúng tạo ra các giá trị mặc định lần lượt làparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
29 vàparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28. Ví dụ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]]
9parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
14 - Điều này lưu trữ một danh sách và nối từng giá trị đối số vào danh sách. Sẽ rất hữu ích khi cho phép một tùy chọn được chỉ định nhiều lần. Nếu giá trị mặc định không trống, thì các phần tử mặc định sẽ xuất hiện trong giá trị được phân tích cú pháp cho tùy chọn, với bất kỳ giá trị nào từ dòng lệnh được thêm vào sau các giá trị mặc định đó. Ví dụ sử dụng$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
0parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
15 - Thao tác này lưu trữ danh sách và nối thêm giá trị được chỉ định bởi đối số từ khóa vào danh sách; . Hành độngparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
15 thường hữu ích khi nhiều đối số cần lưu trữ các hằng số vào cùng một danh sách. Ví dụ$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
1parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
16 - Điều này đếm số lần một đối số từ khóa xảy ra. Ví dụ: điều này hữu ích để tăng mức độ chi tiết$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
2Lưu ý, mặc định sẽ là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22 trừ khi được đặt rõ ràng thành 0parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
17 - Thao tác này sẽ in thông báo trợ giúp đầy đủ cho tất cả các tùy chọn trong trình phân tích cú pháp hiện tại rồi thoát. Theo mặc định, một hành động trợ giúp sẽ tự động được thêm vào trình phân tích cú pháp. Xem để biết chi tiết về cách tạo đầu raparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
18 - Điều này mong đợi một đối số từ khóaargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
85 trong cuộc gọi và in thông tin phiên bản và thoát khi được gọi$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
3args = parser.parse_args[] print[args.filename, args.count, args.verbose]
87 - Điều này lưu trữ một danh sách và mở rộng từng giá trị đối số vào danh sách. Ví dụ sử dụng$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
4Mới trong phiên bản 3. 8
Bạn cũng có thể chỉ định một hành động tùy ý bằng cách chuyển một lớp con Hành động hoặc đối tượng khác thực hiện cùng một giao diện.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]88 có sẵn trong
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 và thêm hỗ trợ cho các hành động boolean như
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36 và
args = parser.parse_args[] print[args.filename, args.count, args.verbose]91
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]5
Mới trong phiên bản 3. 9
Cách được đề xuất để tạo một hành động tùy chỉnh là mở rộng , ghi đè phương thức
args = parser.parse_args[] print[args.filename, args.count, args.verbose]93 và tùy chọn các phương thức
args = parser.parse_args[] print[args.filename, args.count, args.verbose]94 và
args = parser.parse_args[] print[args.filename, args.count, args.verbose]95
Ví dụ về hành động tùy chỉnh
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]6
Để biết thêm chi tiết, xem
cằn nhằn
Các đối tượng ArgumentParser thường liên kết một đối số dòng lệnh với một hành động được thực hiện. Đối số từ khóa
args = parser.parse_args[] print[args.filename, args.count, args.verbose]97 liên kết một số đối số dòng lệnh khác với một hành động. Các giá trị được hỗ trợ là
args = parser.parse_args[] print[args.filename, args.count, args.verbose]
98 [một số nguyên].args = parser.parse_args[] print[args.filename, args.count, args.verbose]
98 đối số từ dòng lệnh sẽ được tập hợp lại thành một danh sách. Ví dụ$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
7Lưu ý rằng
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]]
00 tạo danh sách một mục. Điều này khác với mặc định, trong đó mặt hàng được sản xuất bởi chính nó
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
24. One argument will be consumed from the command line if possible, and produced as a single item. Nếu không có đối số dòng lệnh, giá trị từ sẽ được tạo. Lưu ý rằng đối với các đối số tùy chọn, có một trường hợp bổ sung - có chuỗi tùy chọn nhưng không có đối số dòng lệnh theo sau. Trong trường hợp này, giá trị từ sẽ được tạo ra. Một số ví dụ để minh họa điều này$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
8Một trong những cách sử dụng phổ biến hơn của
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]]
02 là cho phép các tệp đầu vào và đầu ra tùy chọn$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
9
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
25. Tất cả các đối số dòng lệnh hiện tại được tập hợp thành một danh sách. Lưu ý rằng việc có nhiều hơn một đối số vị trí vớiimport 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]]
04 thường không có ý nghĩa gì, nhưng có thể có nhiều đối số tùy chọn vớiimport 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]]
04. Ví dụ$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
0
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
26. Cũng giống nhưparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
25, tất cả các đối số dòng lệnh được tập hợp thành một danh sách. Ngoài ra, một thông báo lỗi sẽ được tạo nếu không có ít nhất một đối số dòng lệnh. Ví dụ$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
1
Nếu đối số từ khóa
args = parser.parse_args[] print[args.filename, args.count, args.verbose]97 không được cung cấp, số lượng đối số được sử dụng được xác định bởi. Nói chung, điều này có nghĩa là một đối số dòng lệnh sẽ được sử dụng và một mục duy nhất [không phải danh sách] sẽ được tạo
hăng sô
Đối 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]]09 của được sử dụng để giữ các giá trị không đổi không được đọc từ dòng lệnh nhưng được yêu cầu cho các hành động khác nhau. Hai cách sử dụng phổ biến nhất của nó là
Khi được gọi vớ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]]
13 hoặcimport 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]]
14. Những hành động này thêm giá trị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]]
09 vào một trong các thuộc tính của đối tượng được trả về bởi. Xem mô tả cho các ví dụ. Nếuimport 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]]
09 không được cung cấp cho , nó sẽ nhận giá trị mặc định làparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22When được gọi với các chuỗi tùy chọn [như
args = parser.parse_args[] print[args.filename, args.count, args.verbose]
35 hoặcargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
36] và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]]
02. Điều này tạo ra một đối số tùy chọn có thể được theo sau bởi 0 hoặc một đối số dòng lệnh. Khi phân tích cú pháp dòng lệnh, nếu gặp phải chuỗi tùy chọn mà không có đối số dòng lệnh nào theo sau nó, giá trị củaimport 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]]
09 sẽ được giả định làparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22 thay thế. Xem mô tả cho các ví dụ
Đã thay đổi trong phiên bản 3. 11. ______21_______26 theo mặc định, kể cả khi
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]]14 hoặc
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]]13.
vỡ nợ
Tất cả các đối số tùy chọn và một số đối số vị trí có thể được bỏ qua tại dòng lệnh. Đối số từ khóa
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]]29 của , có giá trị mặc định là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22, chỉ định giá trị nào sẽ được sử dụng nếu không có đối số dòng lệnh. Đối với các đối số tùy chọn, giá trị
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]]29 được sử dụng khi chuỗi tùy chọn không có ở dòng lệnh
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 102
Nếu không gian tên đích đã có một bộ thuộc tính, hành động mặc định sẽ không ghi đè lên nó
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 103
Nếu giá trị
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]]29 là một chuỗi, trình phân tích cú pháp sẽ phân tích cú pháp giá trị đó như thể đó là một đối số dòng lệnh. Cụ thể, trình phân tích cú pháp áp dụng bất kỳ đối số chuyển đổi nào, nếu được cung cấp, trước khi đặt thuộc tính trên giá trị trả về. Mặt khác, trình phân tích cú pháp sử dụng giá trị như là
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 104
Đối với các đối số vị trí bằng vớ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]]35 hoặc
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]]36, giá trị
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]]29 được sử dụng khi không có đối số dòng lệnh nào
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 105
Việc cung cấ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]]38 khiến không có thuộc tính nào được thêm vào nếu không có đối số dòng lệnh
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 106
loại
Theo mặc định, trình phân tích cú pháp đọc các đối số dòng lệnh dưới dạng các chuỗi đơn giản. Tuy nhiên, khá thường xuyên, chuỗi dòng lệnh thay vào đó nên được hiểu là một loại khác, chẳng hạn như a hoặc. Từ khóa
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]]41 cho phép thực hiện mọi chuyển đổi loại và kiểm tra loại cần thiết
Nếu từ khóa được sử dụng với từ khóa, bộ chuyển đổi kiểu chỉ được áp dụng nếu mặc định là một chuỗi
Đối số của
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]]41 có thể là bất kỳ lệnh gọi nào chấp nhận một chuỗi. Nếu hàm tăng
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]]44, , hoặc , ngoại lệ sẽ bị bắt và một thông báo lỗi được định dạng đẹp sẽ hiển thị. Không có loại ngoại lệ nào khác được xử lý
Các loại và chức năng tích hợp phổ biến có thể được sử dụng làm bộ chuyển đổi loại
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 107
Các chức năng do người dùng xác định cũng có thể được sử dụng
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 108
Hàm này không được khuyến nghị làm công cụ chuyển đổi loại. Tất cả những gì nó làm là chuyển đổi các chuỗi rỗng thành
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29 và các chuỗi không rỗng thành
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag28. Đây thường không phải là những gì được mong muốn
Nói chung, từ khóa
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]]41 là một tiện ích chỉ nên được sử dụng cho các chuyển đổi đơn giản chỉ có thể gây ra một trong ba trường hợp ngoại lệ được hỗ trợ. Bất cứ điều gì có xử lý lỗi hoặc quản lý tài nguyên thú vị hơn nên được thực hiện sau khi các đối số được phân tích cú pháp
Ví dụ: chuyển đổi JSON hoặc YAML có các trường hợp lỗi phức tạp yêu cầu báo cáo tốt hơn mức có thể được cung cấp bởi từ khóa
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]]41. A sẽ không được định dạng tốt và một ngoại 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]]53 sẽ không được xử lý
Thậm chí có những hạn chế khi sử dụng với từ khóa
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]]41. Nếu một đối số sử dụng FileType và sau đó đối số tiếp theo không thành công, lỗi sẽ được báo cáo nhưng tệp không tự động đóng. Trong trường hợp này, tốt hơn là đợi cho đến khi trình phân tích cú pháp chạy xong rồi sử dụng câu lệnh - để quản lý các tệp
Đối với trình kiểm tra loại chỉ kiểm tra đối với một bộ giá trị cố định, hãy cân nhắc sử dụng từ khóa thay thế
lựa chọn
Một số đối số dòng lệnh nên được chọn từ một bộ giá trị bị hạn chế. Chúng có thể được xử lý bằng cách chuyển một đối tượng trình tự làm đối số từ khóa lựa chọn tới. Khi dòng lệnh được phân tích cú pháp, các giá trị đối số sẽ được kiểm tra và thông báo lỗi sẽ hiển thị nếu đối số không phải là một trong các giá trị được chấp nhận
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 109
Lưu ý rằng việc đưa vào chuỗi lựa chọn được kiểm tra sau khi thực hiện bất kỳ chuyển đổi nào, vì vậy loại đối tượng trong chuỗi lựa chọn phải khớp với loại đã chỉ định
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'0
Bất kỳ trình tự nào cũng có thể được chuyển thành giá trị lựa chọn, vì vậy các đối tượng, đối tượng và trình tự tùy chỉnh đều được hỗ trợ
Việc sử dụng không được khuyến nghị vì khó kiểm soát sự xuất hiện của nó trong cách sử dụng, trợ giúp và thông báo lỗi
Các lựa chọn được định dạng sẽ ghi đè metavar mặc định thường được lấy từ dest. Đây thường là những gì bạn muốn vì người dùng không bao giờ nhìn thấy tham số đích. Nếu màn hình này không được mong muốn [có lẽ vì có nhiều lựa chọn], chỉ cần chỉ định rõ ràng
yêu cầu
Nói chung, mô-đun giả định rằng các cờ như
args = parser.parse_args[] print[args.filename, args.count, args.verbose]35 và
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]]63 biểu thị các đối số tùy chọn, luôn có thể được bỏ qua tại dòng lệnh. Để thực hiện một tùy chọn bắt buộc, có thể chỉ định
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag28 cho đối số từ khóa
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]]65 để
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'1
Như ví dụ cho thấy, nếu một tùy chọn được đánh dấu 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]]67, sẽ báo lỗi nếu tùy chọn đó không có ở dòng lệnh
Ghi chú
Các tùy chọn bắt buộc thường được coi là hình thức xấu vì người dùng mong đợi các tùy chọn là tùy chọn và do đó nên tránh chúng khi có thể
Cứu giúp
Giá trị
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]]69 là một chuỗi chứa mô tả ngắn gọn về đối số. Khi người dùng yêu cầu trợ giúp [thường bằng cách sử dụng
args = parser.parse_args[] print[args.filename, args.count, args.verbose]38 hoặc
args = parser.parse_args[] print[args.filename, args.count, args.verbose]39 tại dòng lệnh], các mô 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]]69 này sẽ được hiển thị cùng với mỗi đối số
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'2
Các chuỗ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]]69 có thể bao gồm nhiều định dạng định dạng khác nhau để tránh lặp lại những thứ như tên chương trình hoặc đối số. Các từ xác định có sẵn bao gồm tên chương trình,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag74 và hầu hết các đối số từ khóa cho , e. g.
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]]76,
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]]77, v.v.
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'3
Vì chuỗi trợ giúp hỗ trợ định dạng %, nếu bạn muốn một chữ
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]]78 xuất hiện trong chuỗi trợ giúp, bạn phải thoát khỏi nó dưới dạng
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]]79
hỗ trợ tắt tiếng mục trợ giúp cho một số tùy chọn nhất định, bằng cách đặt giá trị
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]]69 thành
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]]82
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'4
metavar
Khi tạo thông báo trợ giúp, nó cần một số cách để tham chiếu đến từng đối số dự kiến. Theo mặc định, các đối tượng ArgumentParser sử dụng giá trị làm “tên” của từng đối tượng. Theo mặc định, đối với các hành động đối số vị trí, giá trị được sử dụng trực tiếp và đối với các hành động đối số tùy chọn, giá trị được viết hoa. Vì vậy, một đối số vị trí duy nhất vớ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]]84 sẽ được gọi 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]]85. Một đối số tùy chọn duy nhất
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36 phải được theo sau bởi một đối số dòng lệnh duy nhất sẽ được gọi 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]]87. Một ví dụ
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'5
Một tên thay thế có thể được chỉ định vớ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]]88
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'6
Lưu ý rằng
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]]88 chỉ thay đổi tên hiển thị - tên của thuộc tính trên đối tượng vẫn được xác định bởi giá trị
Các giá trị khác nhau của
args = parser.parse_args[] print[args.filename, args.count, args.verbose]97 có thể khiến metavar được sử dụng nhiều lần. Cung cấp một bộ cho
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]]88 chỉ định một cách hiển thị khác cho mỗi đối số
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'7
định mệnh
Most actions add some value as an attribute of the object returned by . Tên của thuộc tính này được xác định bởi đối số từ khóa
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]]95 của. Đối với các hành động đối số vị trí,
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]]95 thường được cung cấp làm đối số đầu tiên cho
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'8
Đối với các hành động đối số tùy chọn, giá trị của
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]]95 thường được suy ra từ các chuỗi tùy chọn. tạo ra giá trị của
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]]95 bằng cách lấy chuỗi tùy chọn dài đầu tiên và loại bỏ chuỗi
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]02 ban đầu. Nếu không có chuỗi tùy chọn dài nào được cung cấp, 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]]95 sẽ được lấy từ chuỗi tùy chọn ngắn đầu tiên bằng cách loại bỏ ký tự đầu tiên
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02. Mọi ký tự
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 bên trong sẽ được chuyển đổi thành ký tự
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]06 để đảm bảo chuỗi là tên thuộc tính hợp lệ. Các ví dụ dưới đây minh họa hành vi này
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'9
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]]95 cho phép cung cấp tên thuộc tính tùy chỉnh
>>> parser = argparse.ArgumentParser[description='Process some integers.']0
các lớp hành động
Các lớp hành động triển khai API hành động, một hàm có thể gọi được trả về một hàm có thể gọi được để xử lý các đối số từ dòng lệnh. Bất kỳ đối tượng nào tuân theo API này đều có thể được chuyển dưới dạng tham số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64 thành
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38lớp argparse. Hành động[option_strings , dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None]
Các đối tượng hành động được ArgumentParser sử dụng để biểu thị thông tin cần thiết để phân tích cú pháp một đối số từ một hoặc nhiều chuỗi từ dòng lệnh. Lớp Hành động phải chấp nhận hai đối số vị trí cộng với bất kỳ đối số từ khóa nào được chuyển đến ngoại trừ chính
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64
Các phiên bản của Hành động [hoặc giá trị trả về của bất kỳ giá trị nào có thể gọi được đối với tham số
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64] phải có các thuộc tính “dest”, “option_strings”, “default”, “type”, “required”, “help”, v.v. xác định. Cách dễ nhất để đảm bảo các thuộc tính này được xác định là gọi
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]13
Các trường hợp hành động phải có thể gọi được, vì vậy các lớp con phải ghi đè phương thức
args = parser.parse_args[] print[args.filename, args.count, args.verbose]93, phương thức này sẽ chấp nhận bốn tham số
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
15 - Đối tượng ArgumentParser chứa hành động này$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
16 - Đối tượng sẽ được trả lại bởi. Hầu hết các hành động thêm thuộc tính vào đối tượng này bằng cách sử dụng$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
20 - Các đối số dòng lệnh được liên kết, với bất kỳ chuyển đổi loại nào được áp dụng. Chuyển đổi loại được chỉ định với đối số từ khóa thành$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
22 - Chuỗi tùy chọn đã được sử dụng để gọi hành động này. Đối số$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
22 là tùy chọn và sẽ vắng mặt nếu hành động được liên kết với đối số vị trí
Phương thức
args = parser.parse_args[] print[args.filename, args.count, args.verbose]93 có thể thực hiện các hành động tùy ý, nhưng thường sẽ đặt các thuộc tính trên
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]16 dựa trê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]]95 và
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]20
Các lớp con hành động có thể định nghĩa một phương thức
args = parser.parse_args[] print[args.filename, args.count, args.verbose]95 không nhận đối số và trả về một chuỗi sẽ được sử dụng khi in cách sử dụng chương trình. Nếu phương pháp đó không được cung cấp, một giá trị mặc định hợp lý sẽ được sử dụng
Phương thức parse_args[]
Trình phân tích đối số. parse_args[args=Không có, namespace=None]Chuyển đổi chuỗi đối số thành đối tượng và gán chúng làm thuộc tính của không gian tên. Trả lại không gian tên đã điền
Các cuộc gọi trước để xác định chính xác đối tượng nào được tạo và cách chúng được chỉ định. Xem tài liệu để biết chi tiết
- Danh sách các chuỗi để phân tích cú pháp. Mặc định được lấy từ
- Một đối tượng để lấy các thuộc tính. Mặc định là một đối tượng trống mới
Cú pháp giá trị tùy chọn
Phương thức này hỗ trợ một số cách chỉ định giá trị của một tùy chọn [nếu cần một tùy chọn]. Trong trường hợp đơn giản nhất, tùy chọn và giá trị của nó được truyền dưới dạng hai đối số riêng biệt
>>> parser = argparse.ArgumentParser[description='Process some integers.']1
Đối với các tùy chọn dài [các tùy chọn có tên dài hơn một ký tự], tùy chọn và giá trị cũng có thể được chuyển dưới dạng một đối số dòng lệnh, sử dụng __
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]34 để phân tách chúng
>>> parser = argparse.ArgumentParser[description='Process some integers.']2
Đối với các tùy chọn ngắn [các tùy chọn chỉ dài một ký tự], tùy chọn và giá trị của nó có thể được nối với nhau
>>> parser = argparse.ArgumentParser[description='Process some integers.']3
Một số tùy chọn ngắn có thể được kết hợp với nhau, chỉ sử dụng một tiền tố
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 duy nhất, miễn là chỉ tùy chọn cuối cùng [hoặc không có tùy chọn nào trong số chúng] yêu cầu giá trị
>>> parser = argparse.ArgumentParser[description='Process some integers.']4
Đối số không hợp lệ
Trong khi phân tích cú pháp dòng lệnh, kiểm tra nhiều lỗi khác nhau, bao gồm tùy chọn không rõ ràng, loại không hợp lệ, tùy chọn không hợp lệ, sai số lượng đối số vị trí, v.v. Khi gặp lỗi như vậy, nó sẽ thoát và in lỗi cùng với thông báo sử dụng
>>> parser = argparse.ArgumentParser[description='Process some integers.']5
Arguments containing args = parser.parse_args[]
print[args.filename, args.count, args.verbose]
02
Phương pháp này cố gắng đưa ra lỗi bất cứ khi nào người dùng mắc lỗi rõ ràng, nhưng một số tình huống vốn đã mơ hồ. Ví dụ: đối số dòng lệnh
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]39 có thể là một nỗ lực để chỉ định một tùy chọn hoặc một nỗ lực để cung cấp một đối số vị trí. Phương pháp thận trọng ở đây. đối số vị trí chỉ có thể bắt đầu bằng
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 nếu chúng trông giống số âm và không có tùy chọn nào trong trình phân tích cú pháp trông giống số âm
>>> parser = argparse.ArgumentParser[description='Process some integers.']6
Nếu bạn có đối số vị trí phải bắt đầu bằng
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 và không giống số âm, bạn có thể chèn đối số giả
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]43 cho biết mọi thứ sau đó là đối số vị trí
>>> parser = argparse.ArgumentParser[description='Process some integers.']7
Viết tắt đối số [khớp tiền tố]
Phương pháp này cho phép các tùy chọn dài được viết tắt thành tiền tố, nếu từ viết tắt rõ ràng [tiền tố khớp với một tùy chọn duy nhất]
>>> parser = argparse.ArgumentParser[description='Process some integers.']8
Một lỗi được tạo ra cho các đối số có thể tạo ra nhiều tùy chọn. Có thể tắt tính năng này bằng cách đặt thành
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29
Ngoài parser.add_argument['filename'] # positional argument
parser.add_argument['-c', '--count'] # option that takes a value
parser.add_argument['-v', '--verbose',
action='store_true'] # on/off flag
04
Đôi khi, có thể hữu ích khi có các đối số phân tích cú pháp ArgumentParser khác với các đối số của. Điều này có thể được thực hiện bằng cách chuyển một danh sách các chuỗi tới. Điều này hữu ích để thử nghiệm tại dấu nhắc tương tác
>>> parser = argparse.ArgumentParser[description='Process some integers.']9
Đối tượng không gian tên
lớp argparse. Không gian tênLớp đơn giản được sử dụng theo mặc định để tạo một đối tượng chứa các thuộc tính và trả về nó
Lớp này đơn giản một cách có chủ ý, chỉ là một lớp con với biểu diễn chuỗi có thể đọc được. Nếu bạn muốn có chế độ xem giống như chính tả của các thuộc tính, bạn có thể sử dụng thành ngữ Python tiêu chuẩ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]']0
Cũng có thể hữu ích khi gán các thuộc tính cho một đối tượng đã tồn tại, thay vì một đối tượng mới. Điều này có thể đạt được bằng cách chỉ định đối số từ khóa
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]55
>>> 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
Tiện ích khác
lệnh phụ
Trình phân tích đối số. add_subparsers[[title][, description][, prog][, parser_class][, action][, option_strings][, dest][, required][, help][, metavar]]Nhiều chương trình chia chức năng của chúng thành một số lệnh con, ví dụ: chương trình
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]56 có thể gọi các lệnh con như
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]57,
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]58 và
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]59. Tách chức năng theo cách này có thể là một ý tưởng đặc biệt hay khi một chương trình thực hiện một số chức năng khác nhau yêu cầu các loại đối số dòng lệnh khác nhau. hỗ trợ việc tạo các lệnh con như vậy với phương thức. Phương thức này thường được gọi không có đối số và trả về một đối tượng hành động đặc biệt. Đối tượng này có một phương thức duy nhất,
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]63, lấy tên lệnh và bất kỳ đối số hàm tạo nào, đồng thời trả về một đối tượng có thể được sửa đổi như bình thường
Mô tả các thông số
tiêu đề - tiêu đề cho nhóm trình phân tích cú pháp phụ trong đầu ra trợ giúp;
mô tả - mô tả cho nhóm trình phân tích cú pháp phụ trong đầu ra trợ giúp, theo mặc định là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22prog - thông tin sử dụng sẽ được hiển thị với trợ giúp của lệnh phụ, theo mặc định, tên của chương trình và bất kỳ đối số vị trí nào trước đối số trình phân tích cú pháp phụ
parser_class - lớp sẽ được sử dụng để tạo các thể hiện của trình phân tích cú pháp phụ, theo mặc định là lớp của trình phân tích cú pháp hiện tại [e. g. ArgumentParser]
- loại hành động cơ bản được thực hiện khi gặp phải đối số này tại dòng lệnh
- tên của thuộc tính mà tên lệnh phụ sẽ được lưu trữ;
- Có phải cung cấp lệnh con hay không, mặc định là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
29 [thêm vào 3. 7]- trợ giúp cho nhóm trình phân tích cú pháp phụ trong đầu ra trợ giúp, theo mặc định là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22- chuỗi trình bày các lệnh phụ có sẵn trong trợ giúp; . }
Một số ví dụ sử dụng
>>> 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
Lưu ý rằng đối tượng được trả về bởi sẽ chỉ chứa các thuộc tính cho trình phân tích cú pháp chính và trình phân tích cú pháp con đã được chọn bởi dòng lệnh [chứ không phải bất kỳ trình phân tích cú pháp con nào khác]. Vì vậy, trong ví dụ trên, khi lệnh
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]72 được chỉ định, chỉ có các thuộc tính
args = parser.parse_args[] print[args.filename, args.count, args.verbose]53 và
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]]85 và khi lệnh
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]75 được chỉ định, chỉ có các thuộc tính
args = parser.parse_args[] print[args.filename, args.count, args.verbose]53 và
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]77
Tương tự, khi một thông báo trợ giúp được yêu cầu từ một bộ phân tích cú pháp con, chỉ phần trợ giúp cho bộ phân tích cú pháp cụ thể đó sẽ được in ra. Thông báo trợ giúp sẽ không bao gồm thông báo trình phân tích cú pháp cha hoặc trình phân tích cú pháp anh chị em. [Tuy nhiên, một thông báo trợ giúp cho mỗi lệnh subparser có thể được cung cấp bằng cách cung cấp đối số
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]78 cho
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]63 như 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]']3
Phương pháp này cũng hỗ trợ các đối số từ khóa
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]81 và
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]82. Khi có một trong hai, các lệnh của trình phân tích cú pháp con sẽ xuất hiện trong nhóm riêng của chúng trong đầu ra trợ giúp. Ví dụ
>>> 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
Furthermore,
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]83 supports an additional
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]84 argument, which allows multiple strings to refer to the same subparser. Ví dụ này, chẳng hạn như
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]56, bí danh
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]86 là cách viết tắt của
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]87
>>> 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
Một cách đặc biệt hiệu quả để xử lý các lệnh phụ là kết hợp việc sử dụng phương thức với các lệnh gọi để mỗi trình phân tích cú pháp con biết hàm Python nào sẽ thực thi. Ví dụ
>>> 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]']6
Bằng cách này, bạn có thể thực hiện công việc gọi hàm thích hợp sau khi quá trình phân tích cú pháp đối số hoàn tất. Liên kết các chức năng với các hành động như thế này thường là cách dễ dàng nhất để xử lý các hành động khác nhau cho mỗi trình phân tích cú pháp con của bạn. Tuy nhiên, nếu cần kiểm tra tên của trình phân tích con đã được gọi, đối số từ khóa
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]]95 cho cuộc gọi sẽ hoạt động
>>> 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]']7
Đã thay đổi trong phiên bản 3. 7. Đối số từ khóa bắt buộc mới.
đối tượng FileType
lớp argparse. Loại tệp[chế độ=', bufsize=- 1, encoding=None, errors=None]Nhà máy tạo các đối tượng có thể được chuyển đến đối số kiểu của. Các đối số có đối tượng là loại của chúng sẽ mở các đối số dòng lệnh dưới dạng tệp với các chế độ, kích thước bộ đệm, mã hóa và xử lý lỗi được yêu cầu [xem hàm để biết thêm chi tiết]
>>> 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]']8
Các đối tượng FileType hiểu đối số giả
args = parser.parse_args[] print[args.filename, args.count, args.verbose]08 và tự động chuyển đổi đối số này thành các đối tượng có thể đọc được và cho các đối tượng có thể ghi
>>> 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]']9
Mới trong phiên bản 3. 4. Các đối số từ khóa mã hóa và lỗi.
Nhóm đối số
Trình phân tích đối số. add_argument_group[title=Không có, description=None]Theo mặc định, nhóm các đối số dòng lệnh thành “đối số vị trí” và “tùy chọn” khi hiển thị thông báo trợ giúp. Khi có một nhóm các đối số theo khái niệm tốt hơn so với nhóm mặc định này, các nhóm thích hợp có thể được tạo bằng phương thức
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]0
Phương thức trả về một đối tượng nhóm đối số có một phương thức giống như một đối tượng thông thường. Khi một đối số được thêm vào nhóm, trình phân tích cú pháp xử lý đối số đó giống như một đối số bình thường, nhưng hiển thị đối số trong một nhóm riêng cho các thông báo trợ giúp. Phương thức chấp nhận các đối số tiêu đề và mô tả có thể được sử dụng để tùy chỉnh màn hình này
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]1
Lưu ý rằng mọi đối số không nằm trong nhóm do người dùng xác định của bạn sẽ kết thúc trở lại trong phần "đối số vị trí" và "đối số tùy chọn" thông thường
Đã thay đổi trong phiên bản 3. 11. Việc gọi một nhóm đối số không được dùng nữa. Tính năng này không bao giờ được hỗ trợ và không phải lúc nào cũng hoạt động chính xác. Chức năng tồn tại trên API một cách tình cờ thông qua kế thừa và sẽ bị xóa trong tương lai.
Loại trừ lẫn nhau
Trình phân tích đối số. add_mutually_exclusive_group[bắt buộc=Sai]Tạo một nhóm loại trừ lẫn nhau. sẽ đảm bảo rằng chỉ một trong các đối số trong nhóm loại trừ lẫn nhau xuất hiện trên dòng lệnh
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]2
Phương thức này cũng chấp nhận một đối số bắt buộc, để chỉ ra rằng ít nhất một trong các đối số loại trừ lẫn nhau là bắt buộc
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]3
Lưu ý rằng các nhóm đối số loại trừ lẫn nhau hiện tại không hỗ trợ đối số tiêu đề và mô tả của
Đã thay đổi trong phiên bản 3. 11. Gọi hoặc trên một nhóm loại trừ lẫn nhau không được chấp nhận. Các tính năng này không bao giờ được hỗ trợ và không phải lúc nào cũng hoạt động chính xác. Các chức năng tồn tại trên API một cách tình cờ thông qua kế thừa và sẽ bị xóa trong tương lai.
Mặc định của trình phân tích cú pháp
Trình phân tích đối số. set_defaults[**kwargs]Most of the time, the attributes of the object returned by will be fully determined by inspecting the command-line arguments and the argument actions. cho phép thêm một số thuộc tính bổ sung được xác định mà không cần kiểm tra dòng lệnh
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]4
Lưu ý rằng các giá trị mặc định ở cấp độ trình phân tích cú pháp luôn ghi đè các giá trị mặc định ở cấp độ đối số
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]5
Giá trị mặc định ở cấp độ trình phân tích cú pháp có thể đặc biệt hữu ích khi làm việc với nhiều trình phân tích cú pháp. Xem phương pháp để biết ví dụ về loại này
Trình phân tích đối số. get_default[dest]Nhận giá trị mặc định cho một thuộc tính không gian tên, được đặt bởi một trong hai hoặc bởi
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]6
Trợ giúp in ấn
Trong hầu hết các ứng dụng điển hình, sẽ đảm nhận việc định dạng và in bất kỳ thông báo lỗi hoặc sử dụng nào. Tuy nhiên, một số phương pháp định dạng có sẵn
Trình phân tích đối số. print_usage[tệp=Không]In một mô tả ngắn gọn về cách thức nên được gọi trên dòng lệnh. Nếu tệp là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22, được giả địnhTrình phân tích đối số. print_help[tệp=Không có]
In thông báo trợ giúp, bao gồm cách sử dụng chương trình và thông tin về các đối số đã đăng ký với. Nếu tệp là
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22, được giả định
Ngoài ra còn có các biến thể của các phương thức này chỉ trả về một chuỗi thay vì in nó
Trình phân tích đối số. format_usage[]Trả về một chuỗi chứa một mô tả ngắn gọn về cách gọi nên được gọi trên dòng lệnh
Trình phân tích đối số. format_help[]Trả về một chuỗi chứa thông báo trợ giúp, bao gồm cách sử dụng chương trình và thông tin về các đối số đã đăng ký với
phân tích cú pháp một phần
Trình phân tích đối số. parse_known_args[args=Không có, namespace=None]Đôi khi, một tập lệnh chỉ có thể phân tích cú pháp một vài đối số dòng lệnh, chuyển các đối số còn lại sang một tập lệnh hoặc chương trình khác. Trong những trường hợp này, phương pháp này có thể hữu ích. Nó hoạt động giống như vậy ngoại trừ việc nó không tạo ra lỗi khi có thêm đối số. Thay vào đó, nó trả về một bộ hai mục chứa không gian tên được điền và danh sách các chuỗi đối số còn lại
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]7
Cảnh báo
quy tắc áp dụng cho
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1028. Trình phân tích cú pháp có thể sử dụng một tùy chọn ngay cả khi đó chỉ là tiền tố của một trong các tùy chọn đã biết, thay vì để nó trong danh sách đối số còn lại
Tùy chỉnh phân tích tệp
Trình phân tích đối số. convert_arg_line_to_args[arg_line]Các đối số được đọc từ một tệp [xem đối số từ khóa fromfile_prefix_chars cho hàm tạo] được đọc một đối số trên mỗi dòng. có thể được ghi đè để đọc fancier
Phương thức này nhận một đối số duy nhất arg_line là một chuỗi được đọc từ tệp đối số. Nó trả về một danh sách các đối số được phân tích cú pháp từ chuỗi này. Phương thức được gọi một lần trên mỗi dòng được đọc từ tệp đối số, theo thứ tự
Ghi đè hữu ích của phương thức này là ghi đè coi từng từ được phân tách bằng dấu cách làm đối số. Ví dụ sau minh họa cách thực hiện việc này
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]8
phương thức thoát
Trình phân tích đối số. thoát[trạng thái=0, message=None]Phương thức này kết thúc chương trình, thoát với trạng thái đã chỉ định và nếu được cung cấp, nó sẽ in một thông báo trước đó. Người dùng có thể ghi đè phương thức này để xử lý các bước này theo cách khác
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]9Trình phân tích đối số. lỗi[thông báo]
Phương pháp này in một thông báo sử dụng bao gồm thông báo lỗi tiêu chuẩn và kết thúc chương trình với mã trạng thái là 2
phân tích cú pháp xen kẽ
Trình phân tích đối số. parse_intermixed_args[args=Không có . , namespace=None]ArgumentParser.parse_known_intermixed_args[args=Không có, namespace=None]Một số lệnh Unix cho phép người dùng kết hợp các đối số tùy chọn với các đối số vị trí. Các phương thức và hỗ trợ kiểu phân tích cú pháp này
Các trình phân tích cú pháp này không hỗ trợ tất cả các tính năng argparse và sẽ đưa ra các ngoại lệ nếu các tính năng không được hỗ trợ được sử dụng. Cụ thể, các bộ phân tích con,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag27 và các nhóm loại trừ lẫn nhau bao gồm cả tùy chọn và vị trí không được hỗ trợ
The following example shows the difference between and . cái trước trả về ___24_______38 dưới dạng đối số chưa được phân tích cú pháp, trong khi cái sau thu thập tất cả các vị trí vào ____24_______39
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag00
trả về một bộ hai mục chứa không gian tên được điền và danh sách các chuỗi đối số còn lại. đưa ra lỗi nếu còn bất kỳ chuỗi đối số nào chưa được phân tích cú pháp
Mới trong phiên bản 3. 7
Nâng cấp mã optparse
Originally, the module had attempted to maintain compatibility with . However, was difficult to extend transparently, particularly with the changes required to support the new
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1045 specifiers and better usage messages. Khi hầu hết mọi thứ trong đó đều đã được sao chép hoặc vá lỗi, việc cố gắng duy trì khả năng tương thích ngược dường như không còn thực tế nữa
Mô-đun cải thiện mô-đun thư viện tiêu chuẩn theo một số cách bao gồm
Handling positional arguments
Lệnh phụ hỗ trợ
Allowing alternative option prefixes like
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
49 and$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
50Handling zero-or-more and one-or-more style arguments
Producing more informative usage messages
Cung cấp giao diện đơn giản hơn nhiều cho
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]]
41 vàargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
64 tùy chỉnh
Đường dẫn nâng cấp một phần từ đến
Replace all calls with calls
Replace
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
57 with$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
58 and add additional calls for the positional arguments. Hãy nhớ rằng những gì trước đây được gọi là$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
60, bây giờ trong ngữ cảnh được gọi là$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
62Thay thế bằng cách sử dụng thay vì
Thay thế các hành động gọi lại và các đối số từ khóa
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
66 bằng các đối 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]]
41 hoặcargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
64Thay thế tên chuỗi cho các đối số từ khóa
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]]
41 bằng các đối tượng loại tương ứng [e. g. int, float, complex, etc]Replace
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
70 with and$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
72 and$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
73 with$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
74Thay thế các chuỗi bằng các đối số ngầm định như
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
75 hoặc$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
76 bằng cú pháp Python tiêu chuẩn để sử dụng từ điển để định dạng chuỗi, nghĩa 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]]
76 vàparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
74Làm cách nào để sử dụng dòng lệnh trong Python?
Để chạy tập lệnh Python bằng lệnh python, bạn cần mở một dòng lệnh và nhập từ python hoặc python3 nếu bạn có cả hai phiên bản, theo sau là đường dẫn . $ python3 hello. py Xin chào thế giới. Nếu mọi thứ hoạt động bình thường, sau khi nhấn Enter, bạn sẽ thấy cụm từ Hello World. , just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!What is meant by command line arguments in Python?
Các đối số dòng lệnh của Python là các tham số đầu vào được truyền cho tập lệnh khi thực thi chúng . Hầu như tất cả các ngôn ngữ lập trình đều cung cấp hỗ trợ cho các đối số dòng lệnh. Sau đó, chúng tôi cũng có các tùy chọn dòng lệnh để thiết lập một số tùy chọn cụ thể cho chương trình.Đối số dòng lệnh là gì?
Đối số dòng lệnh là các tham số đơn giản được cung cấp trên dòng lệnh của hệ thống và giá trị của các đối số này được chuyển cho bạn . Khi một chương trình bắt đầu thực thi mà không có sự tương tác của người dùng, các đối số dòng lệnh được sử dụng để chuyển các giá trị hoặc tệp cho chương trình đó.