Hướng dẫn python main command line arguments - đối số dòng lệnh chính của python

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để làm sâu sắc thêm sự hiểu biết của bạn: Giao diện dòng lệnh trong Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Command Line Interfaces in Python

Show

Việc thêm khả năng xử lý các đối số dòng lệnh Python cung cấp giao diện thân thiện với người dùng cho chương trình dòng lệnh dựa trên văn bản của bạn. Nó tương tự như một giao diện người dùng đồ họa dành cho một ứng dụng trực quan mà thao túng bởi các yếu tố hoặc tiện ích đồ họa.Python command line arguments provides a user-friendly interface to your text-based command line program. It’s similar to what a graphical user interface is for a visual application that’s manipulated by graphical elements or widgets.

Python phơi bày một cơ chế để nắm bắt và trích xuất các đối số dòng lệnh Python của bạn. Các giá trị này có thể được sử dụng để sửa đổi hành vi của một chương trình. Ví dụ: nếu chương trình của bạn xử lý dữ liệu được đọc từ một tệp, thì bạn có thể chuyển tên của tệp cho chương trình của mình, thay vì mã hóa giá trị cứng trong mã nguồn của bạn.

Đến cuối hướng dẫn này, bạn sẽ biết:

  • Nguồn gốc của các đối số dòng lệnh Python of Python command line arguments
  • Hỗ trợ cơ bản cho các đối số dòng lệnh Python for Python command line arguments
  • Các tiêu chuẩn hướng dẫn thiết kế giao diện dòng lệnh guiding the design of a command line interface
  • Những điều cơ bản để tùy chỉnh thủ công và xử lý các đối số dòng lệnh Python to manually customize and handle Python command line arguments
  • Các thư viện có sẵn trong Python để giảm bớt sự phát triển của giao diện dòng lệnh phức tạp available in Python to ease the development of a complex command line interface

Nếu bạn muốn một cách thân thiện với người dùng để cung cấp các đối số dòng lệnh Python cho chương trình của bạn mà không cần nhập thư viện chuyên dụng hoặc nếu bạn muốn hiểu rõ hơn về cơ sở chung cho các thư viện hiện có dành riêng để xây dựng giao diện dòng lệnh Python, thì hãy giữ Về đọc!

Giao diện dòng lệnh

Giao diện dòng lệnh (CLI) cung cấp một cách để người dùng tương tác với một chương trình chạy trong trình thông dịch shell dựa trên văn bản. Một số ví dụ về phiên dịch shell là bash trên linux hoặc dấu nhắc lệnh trên windows. Giao diện dòng lệnh được kích hoạt bởi trình thông dịch shell để lộ dấu nhắc lệnh. Nó có thể được đặc trưng bởi các yếu tố sau:command line interface (CLI) provides a way for a user to interact with a program running in a text-based shell interpreter. Some examples of shell interpreters are Bash on Linux or Command Prompt on Windows. A command line interface is enabled by the shell interpreter that exposes a command prompt. It can be characterized by the following elements:

  • Một lệnh hoặc chương trìnhcommand or program
  • Không hoặc nhiều đối số dòng lệnharguments
  • Đầu ra đại diện cho kết quả của lệnhoutput representing the result of the command
  • Tài liệu văn bản được gọi là sử dụng hoặc trợ giúpusage or help

Không phải mọi giao diện dòng lệnh có thể cung cấp tất cả các yếu tố này, nhưng danh sách này cũng không phải là toàn bộ. Sự phức tạp của dòng lệnh dao động từ khả năng truyền một đối số duy nhất, đến nhiều đối số và tùy chọn, giống như một ngôn ngữ cụ thể của miền. Ví dụ: một số chương trình có thể khởi chạy tài liệu web từ dòng lệnh hoặc bắt đầu một trình thông dịch shell tương tác như Python.

Hai ví dụ sau với lệnh Python minh họa mô tả giao diện dòng lệnh:

$ python -c "print('Real Python')"
Real Python

Trong ví dụ đầu tiên này, trình thông dịch Python có tùy chọn

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
7 cho lệnh, trong đó nói rằng sẽ thực thi các đối số dòng lệnh Python theo tùy chọn
$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
7 dưới dạng chương trình Python.command, which says to execute the Python command line arguments following the option
$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
7 as a Python program.

Một ví dụ khác cho thấy cách gọi Python với

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
9 để hiển thị trợ giúp:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]

Hãy thử điều này trong thiết bị đầu cuối của bạn để xem tài liệu trợ giúp hoàn chỉnh.

Di sản c

Các đối số dòng lệnh Python trực tiếp kế thừa từ ngôn ngữ lập trình C. Như Guido Van Rossum đã viết trong phần giới thiệu về Python cho các lập trình viên UNIX/C vào năm 1993, C có ảnh hưởng mạnh mẽ đến Python. Guido đề cập đến các định nghĩa về nghĩa đen, định danh, toán tử và các câu như

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
0,
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
1 hoặc
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
2. Việc sử dụng các đối số dòng lệnh Python cũng bị ảnh hưởng mạnh mẽ bởi ngôn ngữ C.

Để minh họa những điểm tương đồng, hãy xem xét chương trình C sau:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}

Dòng 4 xác định

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
3, là điểm nhập của chương trình C. Lưu ý tốt về các tham số:

  1. $ sha1sum main.c
    125a0f900ff6f164752600550879cbfabb098bc3  main.c
    
    4 là một số nguyên đại diện cho số lượng đối số của chương trình.
    is an integer representing the number of arguments of the program.
  2. $ sha1sum main.c
    125a0f900ff6f164752600550879cbfabb098bc3  main.c
    
    5 là một loạt các con trỏ cho các ký tự chứa tên của chương trình trong phần tử đầu tiên của mảng, tiếp theo là các đối số của chương trình, nếu có, trong các phần tử còn lại của mảng.
    is an array of pointers to characters containing the name of the program in the first element of the array, followed by the arguments of the program, if any, in the remaining elements of the array.

Bạn có thể biên dịch mã ở trên trên Linux với

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
6, sau đó thực thi với
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
7 để có được những điều sau:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main

Trừ khi được thể hiện rõ ràng ở dòng lệnh với tùy chọn

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
8,
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
9 là tên mặc định của trình biên dịch GCC được tạo bởi Trình biên dịch GCC. Nó là viết tắt của đầu ra của trình biên dịch và gợi nhớ đến các tệp thực thi được tạo ra trên các hệ thống UNIX cũ hơn. Quan sát rằng tên của thực thi
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
7 là đối số duy nhất.gcc compiler. It stands for assembler output and is reminiscent of the executables that were generated on older UNIX systems. Observe that the name of the executable
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
7 is the sole argument.

Hãy để thêm vào ví dụ này bằng cách chuyển một vài đối số dòng lệnh Python cho cùng một chương trình:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments

Đầu ra cho thấy số lượng đối số là

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
01 và danh sách các đối số bao gồm tên của chương trình,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
02, theo sau là mỗi từ của cụm từ
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
03, mà bạn đã chuyển ở dòng lệnh.

Việc tổng hợp

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
04 giả định rằng bạn đã sử dụng hệ thống Linux hoặc Mac OS. Trên Windows, bạn cũng có thể biên dịch chương trình C này với một trong các tùy chọn sau:

  • Hệ thống con Windows cho Linux (WSL): Nó có sẵn trong một vài bản phân phối Linux, như Ubuntu, OpenSuse và Debian, trong số những người khác. Bạn có thể cài đặt nó từ Microsoft Store. It’s available in a few Linux distributions, like Ubuntu, OpenSUSE, and Debian, among others. You can install it from the Microsoft Store.
  • Windows Build Tools: Điều này bao gồm các công cụ xây dựng dòng lệnh Windows, trình biên dịch Microsoft C/C ++
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    05 và đầu trước của trình biên dịch có tên
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    06 cho C/C ++.
    This includes the Windows command line build tools, the Microsoft C/C++ compiler
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    05, and a compiler front end named
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    06 for C/C++.
  • Microsoft Visual Studio: Đây là môi trường phát triển tích hợp chính của Microsoft (IDE). Để tìm hiểu thêm về IDE có thể được sử dụng cho cả Python và C trên các hệ điều hành khác nhau, bao gồm Windows, hãy xem Python IDE và trình chỉnh sửa mã (Hướng dẫn). This is the main Microsoft integrated development environment (IDE). To learn more about IDEs that can be used for both Python and C on various operating systems, including Windows, check out Python IDEs and Code Editors (Guide).
  • Dự án MingW-64: Điều này hỗ trợ trình biên dịch GCC trên Windows. This supports the GCC compiler on Windows.

Nếu bạn đã cài đặt Microsoft Visual Studio hoặc Windows Build Tools, thì bạn có thể biên dịch

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
04 như sau:

Bạn sẽ có được một thực thi có tên

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
08 mà bạn có thể bắt đầu với:

C:/>main
Arguments count: 1
Argument      0: main

Bạn có thể thực hiện một chương trình Python,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09, tương đương với chương trình C,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
04, bạn đã thấy ở trên:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")

Bạn không thấy một biến

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
4 như trong ví dụ mã C. Nó không tồn tại trong Python vì
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 là đủ. Bạn có thể phân tích các đối số dòng lệnh Python trong
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 mà không cần phải biết độ dài của danh sách và bạn có thể gọi
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
14 tích hợp nếu cần số lượng đối số của chương trình.

Ngoài ra, lưu ý rằng

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
15, khi được áp dụng cho một ITable, trả về một đối tượng
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
16 có thể phát ra các cặp liên kết chỉ số của một phần tử trong
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
17 với giá trị tương ứng của nó. Điều này cho phép lặp qua nội dung của
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 mà không phải duy trì bộ đếm cho chỉ mục trong danh sách.

Thực thi

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09 như sau:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 chứa thông tin giống như trong chương trình C:

  • Tên của chương trình
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    09 là mục đầu tiên của danh sách.
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    09 is the first item of the list.
  • Các đối số
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    22,
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    23,
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    24 và
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    25 là các yếu tố còn lại trong danh sách.
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    22,
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    23,
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    24, and
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    25 are the remaining elements in the list.

Với phần giới thiệu ngắn gọn này về một vài khía cạnh phức tạp của ngôn ngữ C, giờ đây bạn đã được trang bị một số kiến ​​thức có giá trị để nắm bắt thêm các đối số dòng lệnh Python.

Hai tiện ích từ thế giới Unix

Để sử dụng các đối số dòng lệnh Python trong hướng dẫn này, bạn sẽ thực hiện một số tính năng một phần của hai tiện ích từ hệ sinh thái UNIX:

  1. sha1sum
  2. SEQ

Bạn sẽ có được một số quen thuộc với các công cụ UNIX này trong các phần sau.

$ python -h usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str. (-bb: issue errors) [ ... complete help text not shown ... ] 26

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 Tính toán các băm SHA-1 và nó thường được sử dụng để xác minh tính toàn vẹn của các tệp. Đối với một đầu vào đã cho, một hàm băm luôn trả về cùng một giá trị. Bất kỳ thay đổi nhỏ trong đầu vào sẽ dẫn đến một giá trị băm khác nhau. Trước khi bạn sử dụng tiện ích với các tham số cụ thể, bạn có thể cố gắng hiển thị trợ giúp:hash function always returns the same value. Any minor changes in the input will result in a different hash value. Before you use the utility with concrete parameters, you may try to display the help:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]

Hiển thị trợ giúp của chương trình dòng lệnh là một tính năng phổ biến được phơi bày trong giao diện dòng lệnh.

Để tính toán giá trị băm SHA-1 của nội dung của tệp, bạn tiến hành như sau:

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c

Kết quả cho thấy giá trị băm SHA-1 là trường đầu tiên và tên của tệp là trường thứ hai. Lệnh có thể lấy nhiều hơn một tệp làm đối số:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
0

Nhờ tính năng mở rộng Wildcards của thiết bị đầu cuối UNIX, nó cũng có thể cung cấp các đối số dòng lệnh Python với các ký tự ký tự đại diện. Một nhân vật như vậy là dấu hoa thị hoặc sao (

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
28):

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
1

Shell chuyển đổi

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
29 thành
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
04 và
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09, là hai tệp phù hợp với mẫu
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
29 trong thư mục hiện tại và chuyển chúng đến
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26. Chương trình tính toán băm SHA1 của từng tệp trong danh sách đối số. Bạn có thể thấy rằng, trên Windows, hành vi là khác nhau. Windows không có sự mở rộng ký tự đại diện, vì vậy chương trình có thể phải phù hợp với điều đó. Việc thực hiện của bạn có thể cần phải mở rộng ký tự đại diện trong nội bộ.SHA1 hash of each of the files in the argument list. You’ll see that, on Windows, the behavior is different. Windows has no wildcard expansion, so the program may have to accommodate for that. Your implementation may need to expand wildcards internally.

Không có bất kỳ đối số nào,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 đọc từ đầu vào tiêu chuẩn. Bạn có thể cung cấp dữ liệu cho chương trình bằng cách nhập các ký tự trên bàn phím. Đầu vào có thể kết hợp bất kỳ ký tự nào, bao gồm cả vận chuyển trở lại Enter. Để chấm dứt đầu vào, bạn phải báo hiệu phần cuối của tệp với Enter, theo sau là chuỗi Ctrl+D:Enter. To terminate the input, you must signal the end of file with Enter, followed by the sequence Ctrl+D:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
2

Trước tiên, bạn nhập tên của chương trình,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26, tiếp theo là Enter, và sau đó
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
36 và
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
22, mỗi người cũng theo sau là Enter. Để đóng luồng đầu vào, bạn nhập ctrl+d. Kết quả là giá trị của băm SHA1 được tạo cho văn bản
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
38. Tên của tệp là
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
39. Đây là một quy ước để chỉ ra đầu vào tiêu chuẩn. Giá trị băm giống nhau khi bạn thực hiện các lệnh sau:Enter, and then
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
36 and
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
22, each also followed by Enter. To close the input stream, you type Ctrl+D. The result is the value of the SHA1 hash generated for the text
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
38. The name of the file is
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
39. This is a convention to indicate the standard input. The hash value is the same when you execute the following commands:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
3

Tiếp theo, bạn sẽ đọc một mô tả ngắn về

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40.

$ python -h usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str. (-bb: issue errors) [ ... complete help text not shown ... ] 40

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 tạo ra một chuỗi các số. Ở dạng cơ bản nhất của nó, như tạo ra chuỗi từ 1 đến 5, bạn có thể thực hiện các mục sau:sequence of numbers. In its most basic form, like generating the sequence from 1 to 5, you can execute the following:

Để có được cái nhìn tổng quan về các khả năng được phơi bày bởi

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40, bạn có thể hiển thị trợ giúp tại dòng lệnh:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
4

Đối với hướng dẫn này, bạn sẽ viết một vài biến thể đơn giản hóa là

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 và
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40. Trong mỗi ví dụ, bạn sẽ học một khía cạnh khác nhau hoặc kết hợp các tính năng về các đối số dòng lệnh Python.

Trên Mac OS và Linux,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 và
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 sẽ được cài đặt sẵn, mặc dù các tính năng và thông tin trợ giúp đôi khi có thể khác nhau một chút giữa các hệ thống hoặc phân phối. Nếu bạn sử dụng Windows 10, thì phương pháp thuận tiện nhất là chạy
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 và
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 trong môi trường Linux được cài đặt trên WSL. Nếu bạn không có quyền truy cập vào một thiết bị đầu cuối để hiển thị các tiện ích UNIX tiêu chuẩn, thì bạn có thể có quyền truy cập vào các thiết bị đầu cuối trực tuyến:

  • Tạo một tài khoản miễn phí trên Pythonanywhere và bắt đầu một bảng điều khiển bash. a free account on PythonAnywhere and start a Bash Console.
  • Tạo một thiết bị đầu cuối bash tạm thời trên repl.it. a temporary Bash terminal on repl.it.

Đây là hai ví dụ, và bạn có thể tìm thấy những người khác.

Mảng $ python -h usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str. (-bb: issue errors) [ ... complete help text not shown ... ] 12

Trước khi khám phá một số quy ước được chấp nhận và khám phá cách xử lý các đối số dòng lệnh Python, bạn cần biết rằng hỗ trợ cơ bản cho tất cả các đối số dòng lệnh Python được cung cấp bởi

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12. Các ví dụ trong các phần sau đây cho bạn biết cách xử lý các đối số dòng lệnh Python được lưu trữ trong
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 và để khắc phục các vấn đề điển hình xảy ra khi bạn cố gắng truy cập chúng. Bạn sẽ học:

  • Cách truy cập nội dung của
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12access the content of
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12
  • Cách giảm thiểu tác dụng phụ của bản chất toàn cầu của
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12mitigate the side effects of the global nature of
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12
  • Cách xử lý khoảng trắng trong các đối số dòng lệnh Pythonprocess whitespaces in Python command line arguments
  • Cách xử lý lỗi trong khi truy cập các đối số dòng lệnh Pythonhandle errors while accessing Python command line arguments
  • Cách ăn định dạng ban đầu của các đối số dòng lệnh Python được truyền qua byteingest the original format of the Python command line arguments passed by bytes

Bắt đầu nào!

Hiển thị đối số

Mô -đun

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
55 hiển thị một mảng có tên
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
5 bao gồm các mục sau:

  1. $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    57 chứa tên của chương trình Python hiện tại.
    contains the name of the current Python program.
  2. $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    58, phần còn lại của danh sách, chứa bất kỳ và tất cả các đối số dòng lệnh Python được chuyển cho chương trình.
    , the rest of the list, contains any and all Python command line arguments passed to the program.

Ví dụ sau đây cho thấy nội dung của

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
5

Ở đây, cách thức hoạt động của mã này:

  • Dòng 2 nhập mô -đun Python nội bộ
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    55.
    imports the internal Python module
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    55.
  • Dòng 4 trích xuất tên của chương trình bằng cách truy cập phần tử đầu tiên của danh sách
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12.
    extracts the name of the program by accessing the first element of the list
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12.
  • Dòng 5 hiển thị các đối số dòng lệnh Python bằng cách tìm nạp tất cả các yếu tố còn lại của danh sách
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12.
    displays the Python command line arguments by fetching all the remaining elements of the list
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12.

Thực hiện tập lệnh

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
63 ở trên với danh sách các đối số tùy ý như sau:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
6

Đầu ra xác nhận rằng nội dung của

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
64 là tập lệnh Python
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
63 và các yếu tố còn lại của danh sách
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 chứa các đối số của tập lệnh,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
67.

Để tóm tắt,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 chứa tất cả các đối số dòng lệnh Python
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
63. Khi trình thông dịch Python thực hiện chương trình Python, nó phân tích dòng lệnh và điền vào
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 với các đối số.

Đảo ngược đối số đầu tiên

Bây giờ bạn có đủ nền trên

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12, bạn sẽ hoạt động trên các đối số được truyền ở dòng lệnh. Ví dụ
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72 đảo ngược đối số đầu tiên được truyền ở dòng lệnh:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
7

Trong

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72, quá trình đảo ngược đối số đầu tiên được thực hiện với các bước sau:

  • Dòng 5 tìm kiếm đối số đầu tiên của chương trình được lưu trữ tại Index
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    74 của
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12. Hãy nhớ rằng tên chương trình được lưu trữ tại Index
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    76 của
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12.
    fetches the first argument of the program stored at index
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    74 of
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12. Remember that the program name is stored at index
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    76 of
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12.
  • Dòng 6 in chuỗi đảo ngược.
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    78 là một cách pythonic để sử dụng một thao tác lát cắt để đảo ngược danh sách.
    prints the reversed string.
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    78 is a Pythonic way to use a slice operation to reverse a list.

Bạn thực thi tập lệnh như sau:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
8

Đúng như dự đoán,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72 hoạt động trên
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
80 và đảo ngược đối số duy nhất để xuất ra
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
81. Lưu ý rằng xung quanh chuỗi đa từ
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
80 với các trích dẫn đảm bảo rằng trình thông dịch xử lý nó như một đối số duy nhất, thay vì hai đối số. Bạn sẽ đi sâu vào các dấu phân cách đối số trong một phần sau.argument separators in a later section.

Đột biến $ python -h usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str. (-bb: issue errors) [ ... complete help text not shown ... ] 12

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 có sẵn trên toàn cầu cho chương trình Python đang chạy của bạn. Tất cả các mô -đun được nhập trong quá trình thực hiện quy trình đều có quyền truy cập trực tiếp vào
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12. Truy cập toàn cầu này có thể thuận tiện, nhưng
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 không thể thay đổi. Bạn có thể muốn thực hiện một cơ chế đáng tin cậy hơn để đưa các đối số chương trình đến các mô -đun khác nhau trong chương trình Python của bạn, đặc biệt là trong một chương trình phức tạp với nhiều tệp.globally available to your running Python program. All modules imported during the execution of the process have direct access to
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12. This global access might be convenient, but
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 isn’t immutable. You may want to implement a more reliable mechanism to expose program arguments to different modules in your Python program, especially in a complex program with multiple files.

Quan sát những gì xảy ra nếu bạn giả mạo

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
9

Bạn gọi

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
88 để xóa và trả lại mục cuối cùng trong
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12.

Thực hiện tập lệnh ở trên:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
0

Lưu ý rằng đối số thứ tư không còn được bao gồm trong

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12.

Trong một kịch bản ngắn, bạn có thể dựa vào quyền truy cập toàn cầu vào

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12, nhưng trong một chương trình lớn hơn, bạn có thể muốn lưu trữ các đối số trong một biến riêng biệt. Ví dụ trước có thể được sửa đổi như sau:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
1

Lần này, mặc dù

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 bị mất yếu tố cuối cùng,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
93 đã được bảo tồn một cách an toàn.
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
93 là toàn cầu và bạn có thể vượt qua nó để phân tích các đối số theo logic của chương trình của bạn. Trình quản lý gói Python,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
95, sử dụng phương pháp này. Tại đây, một đoạn trích ngắn của mã nguồn
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
95:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
2

Trong đoạn mã này được lấy từ mã nguồn

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
95,
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
3 lưu vào
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
93, lát của
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 chỉ chứa các đối số chứ không phải tên tệp.
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 vẫn chưa được xử lý và
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
93 bị ảnh hưởng bởi bất kỳ thay đổi vô tình nào đối với
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12.

Thoát khỏi các ký tự khoảng trắng

Trong ví dụ

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72 mà bạn đã thấy trước đó, đối số đầu tiên và duy nhất là
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
80 và kết quả là
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
81. Đối số bao gồm một khoảng cách khoảng trắng giữa
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
07 và
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
08, và nó cần phải được thoát ra.

Trên Linux, khoảng trắng có thể được thoát ra bằng cách thực hiện một trong những điều sau đây:

  1. Xung quanh các đối số với các trích dẫn đơn (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    09)
    the arguments with single quotes (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    09)
  2. Xung quanh các đối số với dấu ngoặc kép (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    10)
    the arguments with double quotes (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    10)
  3. Tiền tố mỗi không gian bằng dấu gạch chéo ngược (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    11)
    each space with a backslash (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    11)

Không có một trong các giải pháp thoát,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72 lưu trữ hai đối số,
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
07 trong
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
14 và
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
08 trong
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
16:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
3

Đầu ra ở trên cho thấy tập lệnh chỉ đảo ngược

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
07 và
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
08 bị bỏ qua. Để đảm bảo cả hai đối số được lưu trữ, bạn cần phải bao quanh chuỗi tổng thể với dấu ngoặc kép (
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
10).

Bạn cũng có thể sử dụng dấu gạch chéo ngược (

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
11) để thoát khỏi khoảng trắng:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
4

Với dấu gạch chéo ngược (

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
11), Shell lệnh hiển thị một đối số duy nhất cho Python, và sau đó là
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72.

Trong các shell UNIX, bộ phân cách trường nội bộ (IFS) định nghĩa các ký tự được sử dụng làm dấu phân cách. Nội dung của biến shell,

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
23, có thể được hiển thị bằng cách chạy lệnh sau:delimiters. The content of the shell variable,
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
23, can be displayed by running the following command:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
5

Từ kết quả ở trên,

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
24, bạn xác định ba dấu phân cách:

  1. Không gian (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    25)
    (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    25)
  2. Tab (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    26)
    (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    26)
  3. NEWLINE (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    27)
    (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    27)

Tiền tố một không gian với dấu gạch chéo ngược (

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
11) bỏ qua hành vi mặc định của không gian dưới dạng dấu phân cách trong chuỗi
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
80. Điều này dẫn đến một khối văn bản như dự định, thay vì hai.

Lưu ý rằng, trên Windows, giải thích khoảng trắng có thể được quản lý bằng cách sử dụng kết hợp các trích dẫn kép. Nó có một chút phản trực giác bởi vì, trong thiết bị đầu cuối Windows, một trích dẫn kép (

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
10) được hiểu là một sự chuyển đổi sang vô hiệu hóa và sau đó để kích hoạt các ký tự đặc biệt như không gian, tab hoặc ống (
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
31).space, tab, or pipe (
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
31).

Kết quả là, khi bạn bao quanh nhiều hơn một chuỗi với dấu ngoặc kép, thiết bị đầu cuối Windows diễn giải trích dẫn kép đầu tiên như một lệnh để bỏ qua các ký tự đặc biệt và trích dẫn đôi thứ hai là một để giải thích các ký tự đặc biệt.ignore special characters and the second double quote as one to interpret special characters.

Với thông tin này, nó có thể an toàn khi cho rằng xung quanh nhiều hơn một chuỗi với các trích dẫn kép sẽ cung cấp cho bạn hành vi mong đợi, đó là phơi bày nhóm các chuỗi như một đối số duy nhất. Để xác nhận hiệu ứng đặc biệt này của trích dẫn kép trên dòng lệnh Windows, hãy quan sát hai ví dụ sau:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
6

Trong ví dụ trên, bạn có thể suy luận trực giác rằng

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
80 được hiểu là một đối số duy nhất. Tuy nhiên, nhận ra những gì xảy ra khi bạn sử dụng một trích dẫn kép duy nhất:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
7

Lời nhắc lệnh chuyển toàn bộ chuỗi

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
80 như một đối số duy nhất, theo cách tương tự như thể đối số là
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
80. Trong thực tế, lời nhắc lệnh Windows coi báo giá kép duy nhất là một công tắc để vô hiệu hóa hành vi của khoảng trắng làm dấu phân cách và chuyển bất cứ thứ gì theo trích dẫn kép như một đối số duy nhất.

Để biết thêm thông tin về các hiệu ứng của trích dẫn kép trong thiết bị đầu cuối Windows, hãy xem một cách tốt hơn để hiểu trích dẫn và thoát khỏi các đối số dòng lệnh Windows.

Xử lý lỗi

Đối số dòng lệnh Python là chuỗi lỏng lẻo. Nhiều điều có thể sai, vì vậy, một ý tưởng tốt để cung cấp cho người dùng chương trình của bạn một số hướng dẫn trong trường hợp họ vượt qua các đối số không chính xác tại dòng lệnh. Ví dụ:

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72 mong đợi một đối số và nếu bạn bỏ qua nó, thì bạn sẽ gặp lỗi:loose strings. Many things can go wrong, so it’s a good idea to provide the users of your program with some guidance in the event they pass incorrect arguments at the command line. For example,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72 expects one argument, and if you omit it, then you get an error:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
8

Ngoại lệ Python

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
36 được nâng lên và dấu vết tương ứng cho thấy lỗi được gây ra bởi biểu thức
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
37. Thông điệp của ngoại lệ là
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
38. Bạn đã không vượt qua một đối số ở dòng lệnh, vì vậy, không có gì trong danh sách
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 tại Index
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
74.

Đây là một mô hình phổ biến có thể được giải quyết theo một vài cách khác nhau. Đối với ví dụ ban đầu này, bạn sẽ giữ nó ngắn gọn bằng cách bao gồm biểu thức

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
37 trong khối
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
42. Sửa đổi mã như sau:

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
9

Biểu thức trên dòng 4 được bao gồm trong một khối

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
42. Dòng 8 làm tăng ngoại lệ tích hợp
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
44. Nếu không có đối số nào được chuyển đến
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
45, thì quá trình này thoát ra với mã trạng thái là
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
74 sau khi in cách sử dụng. Lưu ý sự tích hợp của
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
64 trong thông báo lỗi. Nó phơi bày tên của chương trình trong thông báo sử dụng. Bây giờ, khi bạn thực hiện cùng một chương trình mà không có bất kỳ đối số dòng lệnh Python nào, bạn có thể thấy đầu ra sau:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
0

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
72 didn có một cuộc tranh luận được thông qua tại dòng lệnh. Do đó, chương trình tăng
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
44 với thông báo lỗi. Điều này khiến chương trình thoát với trạng thái
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
74, hiển thị khi bạn in biến đặc biệt
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
51 với
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
52.

Tính toán $ python -h usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str. (-bb: issue errors) [ ... complete help text not shown ... ] 26

Bạn có thể viết một tập lệnh khác để chứng minh rằng, trên các hệ thống giống như UNIX, các đối số dòng lệnh Python được truyền bởi các byte từ HĐH. Tập lệnh này lấy một chuỗi làm đối số và đưa ra băm Sha-1 thập lục phân của đối số:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
1

Điều này được truyền cảm hứng một cách lỏng lẻo bởi

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26, nhưng nó cố tình xử lý một chuỗi thay vì nội dung của một tệp. Trong
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
55, các bước để nhập các đối số dòng lệnh Python và để đưa ra kết quả là như sau:

  • Dòng 6 lưu trữ nội dung của đối số đầu tiên trong
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56.
    stores the content of the first argument in
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56.
  • Dòng 7 khởi tạo thuật toán SHA1. instantiates a SHA1 algorithm.
  • Dòng 8 cập nhật đối tượng băm SHA1 với nội dung của đối số chương trình đầu tiên. Lưu ý rằng
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    57 lấy một mảng byte làm đối số, do đó, cần phải chuyển đổi
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56 từ một chuỗi thành mảng byte.
    updates the SHA1 hash object with the content of the first program argument. Note that
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    57 takes a byte array as an argument, so it’s necessary to convert
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56 from a string to a bytes array.
  • Dòng 9 in một biểu diễn thập lục phân của băm SHA1 được tính toán trên dòng 8. prints a hexadecimal representation of the SHA1 hash computed on line 8.

Khi bạn chạy tập lệnh bằng một đối số, bạn sẽ nhận được điều này:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
2

Để giữ ngắn gọn ví dụ, tập lệnh

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
55 không xử lý các đối số dòng lệnh Python bị thiếu. Xử lý lỗi có thể được giải quyết trong tập lệnh này giống như cách bạn đã làm trong
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
45.

Từ tài liệu

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12, bạn tìm hiểu rằng để có được các byte gốc của các đối số dòng lệnh Python, bạn có thể sử dụng
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
62. Bằng cách trực tiếp lấy các byte từ
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
14, bạn không cần phải thực hiện chuyển đổi chuỗi thành bytes của
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
56:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
3

Sự khác biệt chính giữa

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
55 và
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
66 được tô sáng trong các dòng sau:

  • Dòng 7 dân cư
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56 với các byte gốc được truyền cho các đối số dòng lệnh Python.
    populates
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56 with the original bytes passed to the Python command line arguments.
  • Dòng 9 vượt qua
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56 như một đối số cho
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    69, nhận được một đối tượng giống như byte.
    passes
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    56 as an argument to
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    69, which receives a bytes-like object.

Thực thi

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
66 để so sánh đầu ra:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
4

Giá trị thập lục phân của băm SHA1 giống như trong ví dụ

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
55 trước đó.

Giải phẫu của dòng lệnh Python

Bây giờ, bạn đã khám phá một vài khía cạnh của các đối số dòng lệnh Python, đáng chú ý nhất là

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12, bạn sẽ áp dụng một số tiêu chuẩn được các nhà phát triển sử dụng thường xuyên trong khi thực hiện giao diện dòng lệnh.

Đối số dòng lệnh Python là một tập hợp con của giao diện dòng lệnh. Chúng có thể bao gồm các loại đối số khác nhau:

  1. Tùy chọn sửa đổi hành vi của một lệnh hoặc chương trình cụ thể. modify the behavior of a particular command or program.
  2. Đối số đại diện cho nguồn hoặc đích sẽ được xử lý. represent the source or destination to be processed.
  3. Các tiểu ban cho phép một chương trình xác định nhiều hơn một lệnh với tập hợp các tùy chọn và đối số tương ứng. allow a program to define more than one command with the respective set of options and arguments.

Trước khi bạn đi sâu hơn vào các loại đối số khác nhau, bạn sẽ nhận được một cái nhìn tổng quan về các tiêu chuẩn được chấp nhận đã hướng dẫn thiết kế giao diện và đối số dòng lệnh. Chúng đã được tinh chỉnh kể từ sự ra đời của thiết bị đầu cuối máy tính vào giữa những năm 1960.

Tiêu chuẩn

Một số tiêu chuẩn có sẵn cung cấp một số định nghĩa và hướng dẫn để thúc đẩy tính nhất quán để thực hiện các lệnh và đối số của chúng. Đây là các tiêu chuẩn và tài liệu tham khảo chính của Unix:standards provide some definitions and guidelines to promote consistency for implementing commands and their arguments. These are the main UNIX standards and references:

  • Công ước Tiện ích Posix
  • Các tiêu chuẩn GNU cho các giao diện dòng lệnh
  • DOCOPT

Các tiêu chuẩn trên xác định các hướng dẫn và danh pháp cho bất cứ điều gì liên quan đến các chương trình và các đối số dòng lệnh Python. Các điểm sau đây là các ví dụ được lấy từ các tài liệu tham khảo đó:

  • POSIX::
    • Một chương trình hoặc tiện ích được theo sau bởi các tùy chọn, tùy chọn-argument và toán hạng.
    • Tất cả các tùy chọn nên được đi trước với ký tự dấu gạch nối hoặc trừ (
      $ python -h
      usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
      Options and arguments (and corresponding environment variables):
      -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
               and comparing bytes/bytearray with str. (-bb: issue errors)
      [ ... complete help text not shown ... ]
      
      39).
    • Tùy chọn-âm không nên là tùy chọn.
  • GNU::
    • Tất cả các chương trình sẽ hỗ trợ hai tùy chọn tiêu chuẩn, đó là
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      74 và
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      75.
    • Các tùy chọn được đặt tên dài tương đương với các tùy chọn kiểu UNIX đơn lẻ. Một ví dụ là
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      76 và
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      77.
  • docopt::
    • Các tùy chọn ngắn có thể được xếp chồng lên nhau, có nghĩa là
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      78 tương đương với
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      79.
    • Tùy chọn dài có thể có các đối số được chỉ định sau một không gian hoặc dấu bằng (
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      80). Tùy chọn dài
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      81 tương đương với
       1// main.c
       2#include 
       3
       4int main(int argc, char *argv[]) {
       5    printf("Arguments count: %d\n", argc);
       6    for (int i = 0; i < argc; i++) {
       7        printf("Argument %6d: %s\n", i, argv[i]);
       8    }
       9    return 0;
      10}
      
      82.

Các tiêu chuẩn này xác định các ký hiệu hữu ích khi bạn mô tả một lệnh. Một ký hiệu tương tự có thể được sử dụng để hiển thị việc sử dụng một lệnh cụ thể khi bạn gọi nó với tùy chọn

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
9 hoặc
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75.

Các tiêu chuẩn GNU rất giống với các tiêu chuẩn POSIX nhưng cung cấp một số sửa đổi và tiện ích mở rộng. Đáng chú ý, họ thêm tùy chọn dài mà một tùy chọn được đặt tên đầy đủ có tiền tố với hai dấu gạch nối (

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
85). Ví dụ: để hiển thị trợ giúp, tùy chọn thông thường là
$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
9 và tùy chọn dài là
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75.long option that’s a fully named option prefixed with two hyphens (
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
85). For example, to display the help, the regular option is
$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
9 and the long option is
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75.

Trong các phần sau, bạn sẽ tìm hiểu thêm về từng thành phần dòng lệnh, tùy chọn, đối số và lệnh phụ.

Tùy chọn

Một tùy chọn, đôi khi được gọi là cờ hoặc công tắc, nhằm sửa đổi hành vi của chương trình. Ví dụ: lệnh

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
88 trên Linux liệt kê nội dung của một thư mục nhất định. Không có bất kỳ đối số nào, nó liệt kê các tệp và thư mục trong thư mục hiện tại:option, sometimes called a flag or a switch, is intended to modify the behavior of the program. For example, the command
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
88 on Linux lists the content of a given directory. Without any arguments, it lists the files and directories in the current directory:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
5

Hãy để thêm một vài tùy chọn. Bạn có thể kết hợp

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
89 và
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
90 thành
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
91, thay đổi thông tin được hiển thị trong thiết bị đầu cuối:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
6

Một tùy chọn có thể lấy một đối số, được gọi là một đối tượng tùy chọn. Xem một ví dụ trong hành động với

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
92 bên dưới:option can take an argument, which is called an option-argument. See an example in action with
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
92 below:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
7

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
92 là viết tắt của bãi rác. Tiện ích này hiển thị dữ liệu trong các biểu diễn có thể in khác nhau, như Octal (là mặc định), thập lục phân, thập phân và ASCII. Trong ví dụ trên, nó lấy tệp nhị phân
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
02 và hiển thị 16 byte đầu tiên của tệp ở định dạng thập lục phân. Tùy chọn
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
95 mong đợi một loại là một đối số tùy chọn và
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
96 mong đợi số lượng byte đầu vào.
stands for octal dump. This utility displays data in different printable representations, like octal (which is the default), hexadecimal, decimal, and ASCII. In the example above, it takes the binary file
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
02 and displays the first 16 bytes of the file in hexadecimal format. The option
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
95 expects a type as an option-argument, and
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
96 expects the number of input bytes.

Trong ví dụ trên,

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
95 được đưa ra loại
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
98, viết tắt của thập lục phân và một byte trên mỗi số nguyên. Điều này được theo sau bởi
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
99 để hiển thị các ký tự có thể in ở cuối dòng đầu vào.
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
96 lấy
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
01 như một đối tượng tùy chọn để giới hạn số lượng byte đầu vào đến 16.

Tranh luận

Các đối số cũng được gọi là toán hạng hoặc tham số trong các tiêu chuẩn POSIX. Các đối số đại diện cho nguồn hoặc đích của dữ liệu mà lệnh hoạt động. Ví dụ: lệnh

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
02, được sử dụng để sao chép một hoặc nhiều tệp vào tệp hoặc thư mục, lấy ít nhất một nguồn và một mục tiêu:arguments are also called operands or parameters in the POSIX standards. The arguments represent the source or the destination of the data that the command acts on. For example, the command
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
02, which is used to copy one or more files to a file or a directory, takes at least one source and one target:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
8

Trong dòng 4,

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
02 có hai đối số:

  1. $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    02: Tệp nguồn
    the source file
  2. $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    05: Tệp đích
    the target file

Sau đó, nó sao chép nội dung của

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
02 vào một tệp mới có tên
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
05. Cả
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
02 và
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
05 đều là đối số hoặc toán hạng của chương trình
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
02.

Tiểu ban

Khái niệm về các tiểu ban được ghi lại trong các tiêu chuẩn POSIX hoặc GNU, nhưng nó xuất hiện trong Docopt. Các tiện ích UNIX tiêu chuẩn là các công cụ nhỏ tuân thủ triết lý Unix. Các chương trình UNIX được dự định là các chương trình làm một việc và làm tốt. Điều này có nghĩa là không có tiểu ban là cần thiết.subcommands isn’t documented in the POSIX or GNU standards, but it does appear in docopt. The standard Unix utilities are small tools adhering to the Unix philosophy. Unix programs are intended to be programs that do one thing and do it well. This means no subcommands are necessary.

Ngược lại, một thế hệ chương trình mới, bao gồm

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
11,
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
12,
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
13 và
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
14, đi kèm với một mô hình hơi khác bao gồm các tiểu ban. Họ không nhất thiết phải là một phần của cảnh quan Unix khi họ trải rộng một số hệ điều hành và họ đã triển khai với một hệ sinh thái đầy đủ đòi hỏi một số lệnh.

Lấy

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
11 làm ví dụ. Nó xử lý một số lệnh, mỗi lệnh có thể với bộ tùy chọn, phân tích tùy chọn và đối số riêng của chúng. Các ví dụ sau đây áp dụng cho tiểu ban Git
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
16:

  • $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    17 hiển thị các nhánh của kho lưu trữ git cục bộ.
    displays the branches of the local git repository.
  • $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    18 tạo ra một chi nhánh địa phương
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    19 trong kho lưu trữ địa phương.
    creates a local branch
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    19 in a local repository.
  • $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    20 Xóa chi nhánh địa phương
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    19.
    deletes the local branch
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    19.
  • $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    22 Hiển thị trợ giúp cho tiểu ban
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    17.
    displays the help for the
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    17 subcommand.

Trong hệ sinh thái Python,

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
95 cũng có khái niệm về các tiểu ban. Một số tiểu ban
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
95 bao gồm
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
26,
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
27,
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
28 hoặc
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
29.

các cửa sổ

Trên Windows, các quy ước liên quan đến các đối số dòng lệnh Python hơi khác nhau, đặc biệt, các quy ước liên quan đến các tùy chọn dòng lệnh. Để xác thực sự khác biệt này, hãy lấy

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
30, đây là một Windows gốc có thể thực thi, hiển thị danh sách các quy trình hiện đang chạy. Nó tương tự như
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
31 trên các hệ thống Linux hoặc MacOS. Dưới đây là một ví dụ về cách thực thi
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
30 trong dấu nhắc lệnh trên Windows:

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
9

Lưu ý rằng bộ tách cho một tùy chọn là một dấu gạch chéo phía trước (

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
33) thay vì dấu gạch nối (
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
39) như các quy ước cho các hệ thống UNIX. Đối với khả năng đọc, có một khoảng trống giữa tên chương trình,
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
35 và tùy chọn
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
36, nhưng nó cũng đúng với loại
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
37.

Ví dụ cụ thể ở trên thực thi

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
30 với bộ lọc chỉ hiển thị các quy trình Notepad hiện đang chạy. Bạn có thể thấy rằng hệ thống có hai phiên bản chạy của quy trình Notepad. Mặc dù nó không tương đương, nhưng điều này tương tự như thực hiện lệnh sau trong một thiết bị đầu cuối trên hệ thống giống như UNIX:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
0

Lệnh

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
31 ở trên cho thấy tất cả các quy trình
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
40 đang chạy hiện tại. Hành vi phù hợp với triết lý Unix, vì đầu ra của
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
31 được chuyển đổi bởi hai bộ lọc
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
42. Lệnh
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
42 đầu tiên chọn tất cả các lần xuất hiện của
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
40 và
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
42 thứ hai lọc ra sự xuất hiện của chính
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
42.

Với sự lây lan của các công cụ UNIX xuất hiện trong hệ sinh thái Windows, các quy ước không dành riêng cho Windows cũng được chấp nhận trên Windows.

Hình ảnh

Khi bắt đầu một quá trình Python, các đối số dòng lệnh Python được chia thành hai loại:

  1. Tùy chọn Python: Những ảnh hưởng này ảnh hưởng đến việc thực hiện trình thông dịch Python. Ví dụ: thêm tùy chọn

    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    47 là một phương tiện để tối ưu hóa việc thực hiện chương trình Python bằng cách xóa các câu lệnh
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    48 và
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    49. Có các tùy chọn Python khác có sẵn ở dòng lệnh.
    These influence the execution of the Python interpreter. For example, adding option
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    47 is a means to optimize the execution of a Python program by removing
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    48 and
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    49 statements. There are other Python options available at the command line.

  2. Chương trình Python và các đối số của nó: Theo các tùy chọn Python (nếu có), bạn sẽ tìm thấy chương trình Python, đây là tên tệp thường có phần mở rộng ____350 và các đối số của nó. Theo quy ước, chúng cũng có thể bao gồm các tùy chọn và đối số. Following the Python options (if there are any), you’ll find the Python program, which is a file name that usually has the extension

    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    50, and its arguments. By convention, those can also be composed of options and arguments.

Lấy lệnh sau đây mà dự định thực hiện chương trình

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09, có các tùy chọn và đối số. Lưu ý rằng, trong ví dụ này, trình thông dịch Python cũng có một số tùy chọn, đó là
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
52 và
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
53.

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
1

Trong dòng lệnh ở trên, các tùy chọn là các đối số dòng lệnh Python và được tổ chức như sau:

  • Tùy chọn
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    52 cho Python không ghi các tệp
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    55 trên việc nhập các mô -đun nguồn. Để biết thêm chi tiết về các tệp
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    55, hãy xem phần Trình biên dịch làm gì? Trong hướng dẫn của bạn về mã nguồn cpython.
    tells Python not to write
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    55 files on the import of source modules. For more details about
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    55 files, check out the section What Does a Compiler Do? in Your Guide to the CPython Source Code.
  • Tùy chọn
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    53 là viết tắt của Verbose và bảo Python theo dõi tất cả các báo cáo nhập.
    stands for verbose and tells Python to trace all import statements.
  • Các đối số được chuyển cho
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    09 là hư cấu và đại diện cho hai tùy chọn dài (
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    59 và
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    76) và hai đối số (
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    61 và
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    62).
    are fictitious and represent two long options (
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    59 and
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    76) and two arguments (
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    61 and
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    62).

Ví dụ này về các đối số dòng lệnh Python có thể được minh họa bằng đồ họa như sau:

Hướng dẫn python main command line arguments - đối số dòng lệnh chính của python

Trong chương trình Python

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09, bạn chỉ có quyền truy cập vào các đối số dòng lệnh Python được chèn bởi Python trong
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12. Các tùy chọn Python có thể ảnh hưởng đến hành vi của chương trình nhưng không thể truy cập được trong
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09.

Một vài phương pháp để phân tích các đối số dòng lệnh Python

Bây giờ, bạn sẽ khám phá một vài cách tiếp cận để bắt giữ các tùy chọn, phân tích tùy chọn và toán hạng. Điều này được thực hiện bằng cách phân tích các đối số dòng lệnh Python. Trong phần này, bạn sẽ thấy một số khía cạnh cụ thể của các đối số và kỹ thuật dòng lệnh Python để xử lý chúng. Đầu tiên, bạn sẽ thấy một ví dụ giới thiệu một cách tiếp cận thẳng dựa vào sự hiểu biết danh sách để thu thập và riêng biệt các tùy chọn với các đối số. Sau đó bạn sẽ:parsing Python command line arguments. In this section, you’ll see some concrete aspects of Python command line arguments and techniques to handle them. First, you’ll see an example that introduces a straight approach relying on list comprehensions to collect and separate options from arguments. Then you will:

  • Sử dụng các biểu thức chính quy để trích xuất các phần tử của dòng lệnh regular expressions to extract elements of the command line
  • Tìm hiểu cách xử lý các tệp được truyền ở dòng lệnh how to handle files passed at the command line
  • Nắm bắt đầu vào tiêu chuẩn theo cách tương thích với các công cụ UNIX the standard input in a way that’s compatible with the Unix tools
  • Phân biệt đầu ra thông thường của chương trình với các lỗi the regular output of the program from the errors
  • Thực hiện trình phân tích cú pháp tùy chỉnh để đọc các đối số dòng lệnh Python a custom parser to read Python command line arguments

Điều này sẽ phục vụ như một sự chuẩn bị cho các tùy chọn liên quan đến các mô -đun trong các thư viện tiêu chuẩn hoặc từ các thư viện bên ngoài mà bạn sẽ tìm hiểu về sau trong hướng dẫn này.

Đối với một cái gì đó không phức tạp, mẫu sau, không thực thi đặt hàng và không xử lý các loại tùy chọn, có thể là đủ:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
2

Mục đích của chương trình trên là sửa đổi trường hợp của các đối số dòng lệnh Python. Ba tùy chọn có sẵn:

  • $ sha1sum --help
    Usage: sha1sum [OPTION]... [FILE]...
    Print or check SHA1 (160-bit) checksums.
    
    With no FILE, or when FILE is -, read standard input.
    
      -b, --binary         read in binary mode
      -c, --check          read SHA1 sums from the FILEs and check them
          --tag            create a BSD-style checksum
      -t, --text           read in text mode (default)
      -z, --zero           end each output line with NUL, not newline,
                           and disable file name escaping
    [ ... complete help text not shown ... ]
    
    7 để tận dụng các lập luận
    to capitalize the arguments
  • $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    67 để chuyển đổi các đối số thành chữ hoa
    to convert the arguments to uppercase
  •  1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    89 để chuyển đổi đối số thành chữ thường
    to convert the argument to lowercase

Mã thu thập và phân tách các loại đối số khác nhau bằng cách sử dụng toàn bộ danh sách:

  • Dòng 5 thu thập tất cả các tùy chọn bằng cách lọc trên bất kỳ đối số dòng lệnh Python nào bắt đầu bằng dấu gạch nối (
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    39).
    collects all the options by filtering on any Python command line arguments starting with a hyphen (
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    39).
  • Dòng 6 tập hợp các đối số chương trình bằng cách lọc ra các tùy chọn. assembles the program arguments by filtering out the options.

Khi bạn thực hiện chương trình Python ở trên với một tập hợp các tùy chọn và đối số, bạn sẽ nhận được đầu ra sau:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
3

Cách tiếp cận này có thể đủ trong nhiều tình huống, nhưng nó sẽ thất bại trong các trường hợp sau:

  • Nếu thứ tự là quan trọng và đặc biệt, nếu các tùy chọn sẽ xuất hiện trước các đối số
  • Nếu cần hỗ trợ cho các đối tượng tùy chọn
  • Nếu một số đối số được có tiền tố với dấu gạch nối (
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    39)

Bạn có thể tận dụng các tùy chọn khác trước khi bạn sử dụng thư viện như

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
71 hoặc
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
72.

Biểu cảm thường xuyên

Bạn có thể sử dụng một biểu thức thông thường để thực thi một thứ tự nhất định, các tùy chọn cụ thể và các tùy chọn-argument hoặc thậm chí loại đối số. Để minh họa việc sử dụng biểu thức chính quy để phân tích các đối số dòng lệnh Python, bạn sẽ thực hiện phiên bản Python của

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40, đây là một chương trình in một chuỗi số. Theo các quy ước của DOCOPT, một đặc điểm kỹ thuật cho
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
74 có thể là:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
4

Đầu tiên, hãy nhìn vào một biểu thức thông thường mà Lừa dự định nắm bắt các yêu cầu ở trên:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
5

Để thử nghiệm biểu thức thông thường ở trên, bạn có thể sử dụng đoạn trích được ghi trên biểu thức thông thường 101. Biểu thức chính quy nắm bắt và thực thi một vài khía cạnh của các yêu cầu được đưa ra cho

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40. Cụ thể, lệnh có thể lấy:

  1. Tùy chọn trợ giúp, tóm lại (
    $ sha1sum --help
    Usage: sha1sum [OPTION]... [FILE]...
    Print or check SHA1 (160-bit) checksums.
    
    With no FILE, or when FILE is -, read standard input.
    
      -b, --binary         read in binary mode
      -c, --check          read SHA1 sums from the FILEs and check them
          --tag            create a BSD-style checksum
      -t, --text           read in text mode (default)
      -z, --zero           end each output line with NUL, not newline,
                           and disable file name escaping
    [ ... complete help text not shown ... ]
    
    9) hoặc định dạng dài (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    75), được chụp dưới dạng một nhóm được đặt tên là
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    78
    , in short (
    $ sha1sum --help
    Usage: sha1sum [OPTION]... [FILE]...
    Print or check SHA1 (160-bit) checksums.
    
    With no FILE, or when FILE is -, read standard input.
    
      -b, --binary         read in binary mode
      -c, --check          read SHA1 sums from the FILEs and check them
          --tag            create a BSD-style checksum
      -t, --text           read in text mode (default)
      -z, --zero           end each output line with NUL, not newline,
                           and disable file name escaping
    [ ... complete help text not shown ... ]
    
    9) or long format (
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    75), captured as a named group called
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    78
  2. Tùy chọn phân tách,
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    90 hoặc
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    80, lấy một đối số tùy chọn và được nắm bắt như nhóm được đặt tên là
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    81
    ,
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    90 or
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    80, taking an optional argument, and captured as named group called
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    81
  3. Lên đến ba toán hạng số nguyên, tương ứng được chụp là
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    82,
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    83 và
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    84
    , respectively captured as
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    82
    ,
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    83
    , and
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    84

Để rõ ràng, mẫu

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
85 ở trên sử dụng cờ
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
86 trên dòng 11. Điều này cho phép bạn truyền biểu thức chính quy qua một vài dòng để tăng cường khả năng đọc. Mẫu xác thực như sau:

  • Lệnh đối số: Tùy chọn và đối số dự kiến ​​sẽ được quy định theo một thứ tự nhất định. Ví dụ, các tùy chọn được mong đợi trước các đối số.: Options and arguments are expected to be laid out in a given order. For example, options are expected before the arguments.
  • Giá trị tùy chọn **: Chỉ
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    75,
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    90 hoặc
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    80 được mong đợi dưới dạng tùy chọn.
    **: Only
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    75,
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    90, or
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    80 are expected as options.
  • Đối số độc quyền lẫn nhau: Tùy chọn
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    75 không tương thích với các tùy chọn hoặc đối số khác.
    : The option
     1// main.c
     2#include 
     3
     4int main(int argc, char *argv[]) {
     5    printf("Arguments count: %d\n", argc);
     6    for (int i = 0; i < argc; i++) {
     7        printf("Argument %6d: %s\n", i, argv[i]);
     8    }
     9    return 0;
    10}
    
    75 isn’t compatible with other options or arguments.
  • Loại đối số: Các toán hạng dự kiến ​​sẽ là số nguyên dương hoặc âm.: Operands are expected to be positive or negative integers.

Để biểu thức thông thường có thể xử lý những thứ này, nó cần phải xem tất cả các đối số dòng lệnh Python trong một chuỗi. Bạn có thể thu thập chúng bằng cách sử dụng str.join ():

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
6

Điều này làm cho

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
91 một chuỗi bao gồm tất cả các đối số, ngoại trừ tên chương trình, được phân tách bằng một không gian.

Với mẫu

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
85 ở trên, bạn có thể trích xuất các đối số dòng lệnh Python với chức năng sau:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
7

Mẫu đã xử lý thứ tự của các đối số, tính độc quyền lẫn nhau giữa các tùy chọn và đối số và loại đối số.

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
93 đang áp dụng
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
94 cho dòng đối số để trích xuất các giá trị phù hợp và lưu trữ dữ liệu trong từ điển.

Từ điển bao gồm tên của mỗi nhóm là khóa và giá trị tương ứng của chúng. Ví dụ: nếu giá trị

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
91 là
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75, thì từ điển là
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
97. Nếu
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
91 là
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
99, thì từ điển sẽ trở thành
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
00. Bạn có thể mở rộng khối mã bên dưới để xem việc triển khai
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 với các biểu thức thông thường.

Mã bên dưới thực hiện phiên bản giới hạn của

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 với biểu thức thông thường để xử lý phân tích và xác thực dòng lệnh:
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40
with a regular expression to handle the command line parsing and validation:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
8

Bạn có thể thực thi mã ở trên bằng cách chạy lệnh này:

Điều này sẽ xuất hiện như sau:

Hãy thử lệnh này với các kết hợp khác, bao gồm tùy chọn

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75.

Bạn đã không thấy một tùy chọn phiên bản được cung cấp ở đây. Điều này đã được thực hiện có chủ ý để giảm độ dài của ví dụ. Bạn có thể xem xét thêm tùy chọn phiên bản như một bài tập mở rộng. Như một gợi ý, bạn có thể sửa đổi biểu thức thông thường bằng cách thay thế dòng

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
04 bằng
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
05. Một khối
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
06 bổ sung cũng sẽ cần thiết trong
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
3.

Tại thời điểm này, bạn biết một vài cách để trích xuất các tùy chọn và đối số từ dòng lệnh. Cho đến nay, các đối số dòng lệnh Python chỉ là chuỗi hoặc số nguyên. Tiếp theo, bạn sẽ học cách xử lý các tệp được truyền dưới dạng đối số.

Xử lý tập tin

Bây giờ, thời gian để thử nghiệm với các đối số dòng lệnh Python dự kiến ​​sẽ là tên tệp. Sửa đổi

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
55 để xử lý một hoặc nhiều tệp làm đối số. Bạn sẽ kết thúc với một phiên bản bị hạ cấp của tiện ích
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 gốc, lấy một hoặc nhiều tệp làm đối số và hiển thị băm Sha1 thập lục phân cho mỗi tệp, theo sau là tên của tệp:file names. Modify
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
55 to handle one or more files as arguments. You’ll end up with a downgraded version of the original
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 utility, which takes one or more files as arguments and displays the hexadecimal SHA1 hash for each file, followed by the name of the file:

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
9

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
10 được áp dụng cho dữ liệu được đọc từ mỗi tệp mà bạn đã truyền ở dòng lệnh, thay vì chính chuỗi. Hãy lưu ý rằng
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
69 lấy một đối tượng giống như byte làm đối số và kết quả của việc gọi
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
12 sau khi mở một tệp có chế độ
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
13 sẽ trả về một đối tượng
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
14. Để biết thêm thông tin về việc xử lý nội dung tệp, hãy xem đọc và ghi tệp bằng Python và đặc biệt, phần làm việc với byte.

Sự phát triển của

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
15 từ việc xử lý các chuỗi ở dòng lệnh để thao tác nội dung của các tệp đang giúp bạn tiến gần hơn đến việc triển khai ban đầu của
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26:

C:/>main
Arguments count: 1
Argument      0: main
0

Việc thực hiện chương trình Python với cùng các đối số dòng lệnh Python đưa ra điều này:

C:/>main
Arguments count: 1
Argument      0: main
1

Bởi vì bạn tương tác với trình thông dịch Shell hoặc dấu nhắc lệnh Windows, bạn cũng nhận được lợi ích của việc mở rộng thẻ đại diện do Shell cung cấp. Để chứng minh điều này, bạn có thể sử dụng lại

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09, hiển thị từng đối số với số đối số và giá trị của nó:

C:/>main
Arguments count: 1
Argument      0: main
2

Bạn có thể thấy rằng shell tự động thực hiện mở rộng ký tự đại diện để bất kỳ tệp nào có tên cơ sở khớp với

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
02, bất kể phần mở rộng, là một phần của
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12.

Việc mở rộng ký tự đại diện có sẵn trên Windows. Để có được hành vi tương tự, bạn cần thực hiện nó trong mã của mình. Để tái cấu trúc

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09 để làm việc với việc mở rộng ký tự đại diện, bạn có thể sử dụng
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
21. Ví dụ sau đây hoạt động trên Windows và mặc dù nó không ngắn gọn như
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
09 ban đầu, cùng một mã hoạt động tương tự trên các nền tảng:

C:/>main
Arguments count: 1
Argument      0: main
3

Trong

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
23,
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
24 dựa vào
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
25 để xử lý các ký tự đại diện kiểu vỏ. Bạn có thể xác minh kết quả trên Windows và bất kỳ hệ điều hành nào khác:

C:/>main
Arguments count: 1
Argument      0: main
4

Điều này giải quyết vấn đề xử lý các tệp bằng các ký tự đại diện như dấu hoa thị (

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
28) hoặc dấu câu hỏi (
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
27), nhưng làm thế nào về
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
28?

Nếu bạn không chuyển bất kỳ tham số nào cho tiện ích

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 gốc, thì nó dự kiến ​​sẽ đọc dữ liệu từ đầu vào tiêu chuẩn. Đây là văn bản bạn nhập tại thiết bị đầu cuối kết thúc khi bạn nhập Ctrl+D trên các hệ thống giống như Unix hoặc Ctrl+Z trên Windows. Các chuỗi điều khiển này gửi một kết thúc của tệp (EOF) đến thiết bị đầu cuối, dừng đọc từ
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
28 và trả về dữ liệu đã được nhập.standard input. This is the text you enter at the terminal that ends when you type Ctrl+D on Unix-like systems or Ctrl+Z on Windows. These control sequences send an end of file (EOF) to the terminal, which stops reading from
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
28 and returns the data that was entered.

Trong phần tiếp theo, bạn sẽ thêm vào mã của mình khả năng đọc từ luồng đầu vào tiêu chuẩn.

Đầu vào tiêu chuẩn

Khi bạn sửa đổi triển khai Python trước đó của

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 để xử lý đầu vào tiêu chuẩn bằng cách sử dụng
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
32, bạn sẽ đến gần hơn với
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 ban đầu:

C:/>main
Arguments count: 1
Argument      0: main
5

Hai quy ước được áp dụng cho phiên bản

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26 mới này:

  1. Không có bất kỳ đối số nào, chương trình hy vọng dữ liệu sẽ được cung cấp trong đầu vào tiêu chuẩn,
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    32, đây là đối tượng tệp có thể đọc được.
  2. Khi một dấu gạch nối (
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    39) được cung cấp dưới dạng đối số tệp ở dòng lệnh, chương trình diễn giải nó khi đọc tệp từ đầu vào tiêu chuẩn.

Hãy thử tập lệnh mới này mà không có bất kỳ đối số nào. Nhập Aphorism đầu tiên của Zen of Python, sau đó hoàn thành mục nhập với phím tắt Ctrl+D trên các hệ thống giống như UNIX hoặc Ctrl+Z trên Windows:Ctrl+D on Unix-like systems or Ctrl+Z on Windows:

C:/>main
Arguments count: 1
Argument      0: main
6

Bạn cũng có thể bao gồm một trong các đối số dưới dạng

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
28 được trộn với các đối số tệp khác như SO:

C:/>main
Arguments count: 1
Argument      0: main
7

Một cách tiếp cận khác trên các hệ thống giống UNIX là cung cấp

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
38 thay vì
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
39 để xử lý đầu vào tiêu chuẩn:

C:/>main
Arguments count: 1
Argument      0: main
8

Trên Windows, không có tương đương với

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
38, do đó, sử dụng
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
39 làm đối số tệp hoạt động như mong đợi.

Kịch bản

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
42 không bao gồm tất cả các xử lý lỗi cần thiết, nhưng bạn sẽ bao gồm một số tính năng còn thiếu sau này trong hướng dẫn này.

Đầu ra tiêu chuẩn và lỗi tiêu chuẩn

Xử lý dòng lệnh có thể có mối quan hệ trực tiếp với

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
28 để tôn trọng các quy ước được chi tiết trong phần trước. Sản lượng tiêu chuẩn, mặc dù không liên quan ngay lập tức, vẫn là một mối quan tâm nếu bạn muốn tuân thủ triết lý Unix. Để cho phép các chương trình nhỏ được kết hợp, bạn có thể phải tính đến ba luồng tiêu chuẩn:

  1. $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    28
  2. $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    45
  3. $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    46

Đầu ra của một chương trình trở thành đầu vào của một chương trình khác, cho phép bạn chuỗi các tiện ích nhỏ. Ví dụ: nếu bạn muốn sắp xếp các câu cách ngôn của Zen of Python, thì bạn có thể thực hiện những điều sau đây:

C:/>main
Arguments count: 1
Argument      0: main
9

Đầu ra trên được cắt ngắn để đọc tốt hơn. Bây giờ hãy tưởng tượng rằng bạn có một chương trình xuất ra cùng một dữ liệu nhưng cũng in một số thông tin gỡ lỗi:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
0

Thực hiện tập lệnh Python ở trên đưa ra:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
1

Ellipsis (

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
47) chỉ ra rằng đầu ra đã bị cắt ngắn để cải thiện khả năng đọc.

Bây giờ, nếu bạn muốn sắp xếp danh sách các câu cách ngôn, thì hãy thực thi lệnh như sau:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
2

Bạn có thể nhận ra rằng bạn đã không có ý định có đầu ra gỡ lỗi làm đầu vào của lệnh

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
48. Để giải quyết vấn đề này, bạn muốn gửi dấu vết đến luồng lỗi tiêu chuẩn, thay vào đó là
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
46:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
3

Thực hiện

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
50 để quan sát những điều sau:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
4

Bây giờ, các dấu vết được hiển thị cho thiết bị đầu cuối, nhưng chúng không được sử dụng làm đầu vào cho lệnh

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
48.

Phân tích cú pháp tùy chỉnh

Bạn có thể thực hiện

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 bằng cách dựa vào biểu thức chính quy nếu các đối số không quá phức tạp. Tuy nhiên, mẫu Regex có thể nhanh chóng khiến việc duy trì tập lệnh trở nên khó khăn. Trước khi bạn thử nhận trợ giúp từ các thư viện cụ thể, một cách tiếp cận khác là tạo trình phân tích cú pháp tùy chỉnh. Trình phân tích cú pháp là một vòng lặp lấy từng đối số từng đối số và áp dụng logic tùy chỉnh dựa trên ngữ nghĩa của chương trình của bạn.custom parser. The parser is a loop that fetches each argument one after another and applies a custom logic based on the semantics of your program.

Một triển khai có thể để xử lý các đối số của

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
53 có thể như sau:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
5

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
93 được đưa ra danh sách các đối số mà không có tên tệp Python và sử dụng
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
55 để nhận được lợi ích của
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
56, loại bỏ các yếu tố từ bên trái của bộ sưu tập. Khi các mục của danh sách các đối số mở ra, bạn áp dụng logic mà bạn mong đợi cho chương trình của bạn. Trong
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
93, bạn có thể quan sát như sau:

  • Vòng lặp
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    58 là cốt lõi của hàm và chấm dứt khi không có nhiều đối số hơn để phân tích, khi sự trợ giúp được gọi hoặc khi xảy ra lỗi.
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    58 loop
    is at the core of the function, and terminates when there are no more arguments to parse, when the help is invoked, or when an error occurs.
  • Nếu tùy chọn
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    59 được phát hiện, thì đối số tiếp theo dự kiến ​​là dấu phân cách.
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    59
    option is detected, then the next argument is expected to be the separator.
  • $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    60 lưu trữ các số nguyên được sử dụng để tính toán trình tự. Cần có ít nhất một toán hạng và nhiều nhất là ba.
    stores the integers that are used to calculate the sequence. There should be at least one operand and at most three.

Một phiên bản đầy đủ của mã cho

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
93 có sẵn bên dưới:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
6

Lưu ý rằng một số khía cạnh xử lý lỗi được giữ ở mức tối thiểu để giữ các ví dụ tương đối ngắn.

Cách tiếp cận thủ công này để phân tích các đối số dòng lệnh Python có thể là đủ cho một tập hợp các đối số đơn giản. Tuy nhiên, nó trở nên nhanh chóng dễ bị lỗi khi độ phức tạp tăng lên do như sau:

  • Một số lượng lớn các đối số of arguments
  • Sự phức tạp và sự phụ thuộc lẫn nhau giữa các đối số between arguments
  • Xác nhận để thực hiện chống lại các đối số to perform against the arguments

Cách tiếp cận tùy chỉnh là có thể tái sử dụng và yêu cầu phát minh lại bánh xe trong mỗi chương trình. Đến cuối hướng dẫn này, bạn sẽ cải thiện giải pháp thủ công này và học được một vài phương pháp tốt hơn.

Một vài phương pháp để xác thực các đối số dòng lệnh Python

Bạn đã thực hiện xác thực cho các đối số dòng lệnh Python trong một vài ví dụ như

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
62 và
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
53. Trong ví dụ đầu tiên, bạn đã sử dụng một biểu thức thông thường và trong ví dụ thứ hai, một trình phân tích cú pháp tùy chỉnh.

Cả hai ví dụ này đều tính đến các khía cạnh tương tự. Họ coi các tùy chọn dự kiến ​​là dạng ngắn (

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
90) hoặc dạng dài (
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
80). Họ đã xem xét thứ tự của các đối số để các tùy chọn sẽ không được đặt sau các toán hạng. Cuối cùng, họ đã xem xét loại, số nguyên cho các toán hạng và số lượng đối số, từ một đến ba đối số.options as short-form (
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
90) or long-form (
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
80). They considered the order of the arguments so that options would not be placed after operands. Finally, they considered the type, integer for the operands, and the number of arguments, from one to three arguments.

Nhập xác thực với các lớp dữ liệu Python

Sau đây là một bằng chứng về khái niệm cố gắng xác nhận loại đối số được truyền ở dòng lệnh. Trong ví dụ sau, bạn xác nhận số lượng đối số và loại tương ứng của chúng:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
7

Trừ khi bạn vượt qua tùy chọn

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75 tại dòng lệnh, tập lệnh này mong đợi hai hoặc ba đối số:

  1. Một chuỗi bắt buộc:
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    67
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    67
  2. Một chuỗi bắt buộc:
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    68
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    68
  3. Một số nguyên tùy chọn:
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    69
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    69

Bởi vì tất cả các mục trong

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
12 là các chuỗi, bạn cần chuyển đổi đối số thứ ba tùy chọn thành một số nguyên nếu nó bao gồm các chữ số.
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
71 Xác thực nếu tất cả các ký tự trong một chuỗi là các chữ số. Ngoài ra, bằng cách xây dựng lớp dữ liệu
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
25 với các giá trị của các đối số được chuyển đổi, bạn có được hai xác nhận:data class
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
25 with the values of the converted arguments, you obtain two validations:

  1. Nếu số lượng đối số không tương ứng với số lượng các trường bắt buộc được dự kiến ​​bởi
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    25, thì bạn sẽ gặp lỗi. Đây là tối thiểu hai và tối đa ba trường.
    doesn’t correspond to the number of mandatory fields expected by
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    25, then you get an error. This is a minimum of two and a maximum of three fields.
  2. Nếu các loại sau khi chuyển đổi aren phù hợp với các loại được xác định trong định nghĩa lớp dữ liệu
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    25, thì bạn sẽ gặp lỗi.
    aren’t matching the types defined in the
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    25 data class definition, then you get an error.

Bạn có thể thấy điều này trong hành động với việc thực thi sau:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
8

Trong thực thi ở trên, số lượng đối số là chính xác và loại của mỗi đối số cũng là chính xác.

Bây giờ, thực thi cùng một lệnh nhưng bỏ qua đối số thứ ba:

# main.py
import sys

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")
9

Kết quả cũng thành công vì trường

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
69 được xác định với giá trị mặc định,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
76, do đó lớp dữ liệu
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
25 không yêu cầu.default value,
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
76, so the data class
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
25 doesn’t require it.

Ngược lại, nếu đối số thứ ba không phải là loại đúng kiểu, một chuỗi thay vì số nguyên thì bạn sẽ gặp lỗi:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
0

Giá trị dự kiến ​​

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
78, được bao quanh bởi các trích dẫn, vì vậy nó chia tách. Từ thứ hai của họ,
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
79, là một chuỗi mà xử lý theo tuổi, dự kiến ​​sẽ là một
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
80. Việc xác nhận thất bại.

Tương tự, bạn cũng có thể sử dụng

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
81 để đạt được xác nhận tương tự. Bạn có thể thay thế lớp dữ liệu bằng một lớp xuất phát từ
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
81 và
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
83 sẽ thay đổi như sau:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
1

A

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
81 hiển thị các chức năng như
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
85 chuyển đổi đối tượng thành một từ điển có thể được sử dụng để tra cứu dữ liệu. Nó cũng phơi bày các thuộc tính như
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
86, đây là loại lưu trữ từ điển cho mỗi trường và để biết thêm về
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
86, hãy xem kiểm tra loại Python (Hướng dẫn).

Như được nhấn mạnh trong kiểm tra loại Python (Hướng dẫn), bạn cũng có thể tận dụng các gói hiện có như Enforce, Pydantic và PyTypes để xác nhận nâng cao.

Xác nhận tùy chỉnh

Không giống như những gì bạn đã khám phá trước đó, xác thực chi tiết có thể yêu cầu một số phương pháp tùy chỉnh. Ví dụ: nếu bạn cố gắng thực thi

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
42 với tên tệp không chính xác làm đối số, thì bạn sẽ nhận được như sau:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
2

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
89 không tồn tại, nhưng chương trình cố gắng đọc nó.

Xem lại

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
3 trong
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
42 để xử lý các tệp không tồn tại được truyền ở dòng lệnh:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
3

Để xem ví dụ hoàn chỉnh với xác thực bổ sung này, hãy mở rộng khối mã bên dưới:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
4

Khi bạn thực hiện tập lệnh đã sửa đổi này, bạn sẽ nhận được điều này:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
5

Lưu ý rằng lỗi được hiển thị cho thiết bị đầu cuối được ghi vào

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
46, do đó, nó không can thiệp vào dữ liệu được mong đợi bởi một lệnh sẽ đọc đầu ra của
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
93:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
6

Lệnh này ống đầu ra của

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
93 đến
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
95 chỉ bao gồm trường đầu tiên. Bạn có thể thấy rằng
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
95 bỏ qua thông báo lỗi vì nó chỉ nhận được dữ liệu được gửi đến
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
45.

Thư viện tiêu chuẩn Python

Mặc dù các cách tiếp cận khác nhau mà bạn đã thực hiện để xử lý các đối số dòng lệnh Python, bất kỳ chương trình phức tạp nào cũng có thể tốt hơn là tận dụng các thư viện hiện có để xử lý các giao diện dòng lệnh được yêu cầu bởi các giao diện dòng lệnh tinh vi. Kể từ Python 3.7, có ba trình phân tích cú pháp dòng lệnh trong thư viện tiêu chuẩn:leveraging existing libraries to handle the heavy lifting required by sophisticated command line interfaces. As of Python 3.7, there are three command line parsers in the standard library:

  1. $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    71
  2. $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    99
  3. C:/>main
    Arguments count: 1
    Argument      0: main
    
    00

Mô -đun được đề xuất để sử dụng từ thư viện tiêu chuẩn là

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
71. Thư viện tiêu chuẩn cũng phơi bày
C:/>main
Arguments count: 1
Argument      0: main
00 nhưng nó chính thức không được dùng và chỉ được đề cập ở đây cho thông tin của bạn. Nó được thay thế bởi
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
71 trong Python 3.2 và bạn đã giành chiến thắng khi thấy nó được thảo luận trong hướng dẫn này.

$ gcc -o main main.c $ ./main Arguments count: 1 Argument 0: ./main 71

Bạn sẽ xem lại

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
93, bản sao gần đây nhất của
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
26, để giới thiệu những lợi ích của
$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
71. Để hiệu ứng này, bạn sẽ sửa đổi
$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
3 và thêm
C:/>main
Arguments count: 1
Argument      0: main
09 để khởi tạo
C:/>main
Arguments count: 1
Argument      0: main
10:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
7

Đối với chi phí của một vài dòng hơn so với triển khai trước đó, bạn sẽ có một cách tiếp cận sạch để thêm các tùy chọn

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75 và
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
74 mà trước đây đã tồn tại. Các đối số dự kiến ​​(các tệp được xử lý) đều có sẵn trong trường
C:/>main
Arguments count: 1
Argument      0: main
13 của đối tượng
C:/>main
Arguments count: 1
Argument      0: main
14. Đối tượng này được điền trên dòng 17 bằng cách gọi
C:/>main
Arguments count: 1
Argument      0: main
15.

Để xem tập lệnh đầy đủ với các sửa đổi được mô tả ở trên, hãy mở rộng khối mã bên dưới:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
8

Để minh họa lợi ích ngay lập tức mà bạn có được bằng cách giới thiệu

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
71 trong chương trình này, hãy thực hiện các mục sau:

$ python main.py Python Command Line Arguments
Arguments count: 5
Argument      0: main.py
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
9

Để đi sâu vào các chi tiết của

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
71, hãy xem cách xây dựng các giao diện dòng lệnh trong Python với Argparse.

$ ./main Python Command Line Arguments Arguments count: 5 Argument 0: ./main Argument 1: Python Argument 2: Command Argument 3: Line Argument 4: Arguments 99

$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
99 tìm thấy nguồn gốc của nó trong hàm
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
99 C. Nó tạo điều kiện phân tích các tùy chọn dòng lệnh và xử lý, đối số tùy chọn và đối số. Xem lại
C:/>main
Arguments count: 1
Argument      0: main
21 từ
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
53 để sử dụng
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
99:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
0

C:/>main
Arguments count: 1
Argument      0: main
24 có các đối số sau:

  1. Danh sách đối số thông thường trừ tên tập lệnh,
    C:/>main
    Arguments count: 1
    Argument      0: main
    
    25
  2. Một chuỗi xác định các tùy chọn ngắn
  3. Một danh sách các chuỗi cho các tùy chọn dài

Lưu ý rằng một tùy chọn ngắn theo sau là một dấu hai chấm (

C:/>main
Arguments count: 1
Argument      0: main
26) mong đợi một đối số tùy chọn và một tùy chọn dài được kéo dài với một dấu hiệu tương đương (
 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
80) mong đợi một đối số tùy chọn.

Mã còn lại của

C:/>main
Arguments count: 1
Argument      0: main
28 giống như
$ ./main Python Command Line Arguments
Arguments count: 5
Argument      0: ./main
Argument      1: Python
Argument      2: Command
Argument      3: Line
Argument      4: Arguments
53 và có sẵn trong khối mã bị sụp đổ bên dưới:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
1

Tiếp theo, bạn sẽ xem xét một số gói bên ngoài sẽ giúp bạn phân tích các đối số dòng lệnh Python.

Một vài gói python bên ngoài

Dựa trên các quy ước hiện có mà bạn đã thấy trong hướng dẫn này, có một vài thư viện có sẵn trên Chỉ số gói Python (PYPI) thực hiện nhiều bước nữa để tạo điều kiện cho việc thực hiện và duy trì các giao diện dòng lệnh.

Các phần sau đây cung cấp một cái nhìn thoáng qua về Click và Python Prompt Bộ công cụ. Bạn chỉ được tiếp xúc với khả năng rất hạn chế của các gói này, vì cả hai đều yêu cầu một hướng dẫn đầy đủ nếu không phải là toàn bộ loạt phim để làm cho họ công bằng!

Nhấp chuột

Theo văn bản này, Click có lẽ là thư viện tiên tiến nhất để xây dựng giao diện dòng lệnh tinh vi cho chương trình Python. Nó được sử dụng bởi một số sản phẩm Python, đặc biệt là bình và màu đen. Trước khi bạn thử ví dụ sau, bạn cần cài đặt nhấp vào môi trường ảo Python hoặc môi trường địa phương của bạn. Nếu bạn không quen thuộc với khái niệm môi trường ảo, thì hãy kiểm tra các môi trường ảo Python: một mồi.Click is perhaps the most advanced library to build a sophisticated command line interface for a Python program. It’s used by several Python products, most notably Flask and Black. Before you try the following example, you need to install Click in either a Python virtual environment or your local environment. If you’re not familiar with the concept of virtual environments, then check out Python Virtual Environments: A Primer.

Để cài đặt nhấp chuột, hãy tiến hành như sau:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
2

Vì vậy, làm thế nào có thể nhấp vào giúp bạn xử lý các đối số dòng lệnh Python? Ở đây, một biến thể của chương trình

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 bằng cách sử dụng nhấp chuột:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
3

Cài đặt

C:/>main
Arguments count: 1
Argument      0: main
31 thành
C:/>main
Arguments count: 1
Argument      0: main
32 đảm bảo rằng nhấp chuột không phân tích các đối số tiêu cực là tùy chọn. Số nguyên âm là các đối số
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 hợp lệ.

Như bạn có thể đã quan sát, bạn nhận được rất nhiều miễn phí! Một vài nhà trang trí được chạm khắc tốt là đủ để chôn mã nồi hơi, cho phép bạn tập trung vào mã chính, đó là nội dung của

C:/>main
Arguments count: 1
Argument      0: main
34 trong ví dụ này.

Nhập duy nhất còn lại là

$ gcc -o main main.c
$ ./main
Arguments count: 1
Argument      0: ./main
72. Cách tiếp cận khai báo của trang trí lệnh chính,
C:/>main
Arguments count: 1
Argument      0: main
34, loại bỏ mã lặp đi lặp lại mà nếu không cần thiết. Đây có thể là bất kỳ điều nào sau đây:

  • Xác định quy trình trợ giúp hoặc sử dụng a help or usage procedure
  • Xử lý phiên bản của chương trình the version of the program
  • Nắm bắt và thiết lập các giá trị mặc định cho các tùy chọn and setting up default values for options
  • Xác thực các đối số, bao gồm cả loại arguments, including the type

Việc triển khai

$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
40 mới hầu như không làm trầy xước bề mặt. Click cung cấp nhiều tính năng khác sẽ giúp bạn tạo ra một giao diện dòng lệnh rất chuyên nghiệp:

  • Màu đầu ra
  • Nhắc nhở cho các đối số bị bỏ qua
  • Lệnh và lệnh phụ
  • Xác thực loại đối số
  • Gọi lại trên các tùy chọn và đối số
  • Xác thực đường dẫn tệp
  • Thanh tiến trình

Có nhiều tính năng khác là tốt. Kiểm tra viết các công cụ dòng lệnh Python bằng nhấp chuột để xem thêm các ví dụ cụ thể dựa trên nhấp chuột.

Bộ công cụ nhắc nhở Python

Có các gói Python phổ biến khác đang xử lý vấn đề giao diện dòng lệnh, như Docopt cho Python. Vì vậy, bạn có thể tìm thấy sự lựa chọn của bộ công cụ nhắc nhở một chút phản trực giác.

Bộ công cụ nhắc nhở Python cung cấp các tính năng có thể làm cho ứng dụng dòng lệnh của bạn rời khỏi triết lý Unix. Tuy nhiên, nó giúp thu hẹp khoảng cách giữa giao diện dòng lệnh Arcane và giao diện người dùng đồ họa chính thức. Nói cách khác, nó có thể giúp làm cho các công cụ và chương trình của bạn thân thiện với người dùng hơn.Python Prompt Toolkit provides features that may make your command line application drift away from the Unix philosophy. However, it helps to bridge the gap between an arcane command line interface and a full-fledged graphical user interface. In other words, it may help to make your tools and programs more user-friendly.

Bạn có thể sử dụng công cụ này bên cạnh việc xử lý các đối số dòng lệnh Python như trong các ví dụ trước, nhưng điều này cung cấp cho bạn một đường dẫn đến cách tiếp cận giống UI mà không cần bạn phải phụ thuộc vào bộ công cụ UI Python đầy đủ. Để sử dụng

C:/>main
Arguments count: 1
Argument      0: main
38, bạn cần cài đặt nó với
$ python -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
[ ... complete help text not shown ... ]
95:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
4

Bạn có thể tìm thấy ví dụ tiếp theo một chút giả định, nhưng ý định là thúc đẩy các ý tưởng và đưa bạn ra khỏi các khía cạnh nghiêm ngặt hơn của dòng lệnh đối với các quy ước mà bạn đã thấy trong hướng dẫn này.

Như bạn đã thấy logic cốt lõi của ví dụ này, đoạn mã bên dưới chỉ trình bày mã lệch đáng kể so với các ví dụ trước:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
5

Mã ở trên bao gồm các cách để tương tác và có thể hướng dẫn người dùng nhập vào đầu vào dự kiến ​​và để xác thực đầu vào tương tác bằng cách sử dụng ba hộp thoại:

  1. C:/>main
    Arguments count: 1
    Argument      0: main
    
    40
  2. C:/>main
    Arguments count: 1
    Argument      0: main
    
    41
  3. C:/>main
    Arguments count: 1
    Argument      0: main
    
    42

Bộ công cụ Python Prompt phơi bày nhiều tính năng khác nhằm cải thiện sự tương tác với người dùng. Cuộc gọi đến người xử lý trong

$ sha1sum main.c
125a0f900ff6f164752600550879cbfabb098bc3  main.c
3 được kích hoạt bằng cách gọi một hàm được lưu trữ trong từ điển. Kiểm tra các câu lệnh chuyển đổi/trường hợp mô phỏng trong Python nếu bạn không bao giờ gặp phải thành ngữ Python này trước đây.

Bạn có thể thấy ví dụ đầy đủ của chương trình bằng cách sử dụng

C:/>main
Arguments count: 1
Argument      0: main
38 bằng cách mở rộng khối mã bên dưới:

$ sha1sum --help
Usage: sha1sum [OPTION]... [FILE]...
Print or check SHA1 (160-bit) checksums.

With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read SHA1 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  -z, --zero           end each output line with NUL, not newline,
                       and disable file name escaping
[ ... complete help text not shown ... ]
6

Khi bạn thực thi mã ở trên, bạn đã chào đón một hộp thoại khiến bạn phải hành động. Sau đó, nếu bạn chọn chuỗi hành động, một hộp thoại khác được hiển thị. Sau khi thu thập tất cả các dữ liệu, tùy chọn hoặc đối số cần thiết, hộp thoại biến mất và kết quả được in ở dòng lệnh, như trong các ví dụ trước:

Hướng dẫn python main command line arguments - đối số dòng lệnh chính của python

Khi dòng lệnh phát triển và bạn có thể thấy một số nỗ lực tương tác với người dùng một cách sáng tạo hơn, các gói khác như pyinwirer cũng cho phép bạn tận dụng một cách tiếp cận rất tương tác.

Để khám phá thêm thế giới của giao diện người dùng dựa trên văn bản (TUI), hãy xem các giao diện người dùng console xây dựng và phần bên thứ ba trong hướng dẫn của bạn về chức năng in Python.Text-Based User Interface (TUI), check out Building Console User Interfaces and the Third Party section in Your Guide to the Python Print Function.

Nếu bạn quan tâm đến việc nghiên cứu các giải pháp chỉ dựa vào giao diện người dùng đồ họa, thì bạn có thể xem xét kiểm tra các tài nguyên sau:

  • Cách xây dựng một ứng dụng GUI Python với WxPython
  • Python và Pyqt: Xây dựng máy tính máy tính để bàn GUI
  • Xây dựng một ứng dụng di động với khung Kivy Python

Sự kết luận

Trong hướng dẫn này, bạn đã điều hướng nhiều khía cạnh khác nhau của các đối số dòng lệnh Python. Bạn nên cảm thấy chuẩn bị để áp dụng các kỹ năng sau vào mã của mình:

  • Các quy ước và tiêu chuẩn giả của các đối số dòng lệnh Pythonconventions and pseudo-standards of Python command line arguments
  • Nguồn gốc của
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12 trong Pythonorigins of
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12 in Python
  • Việc sử dụng
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12 để cung cấp sự linh hoạt trong việc chạy các chương trình Python của bạnusage of
    $ python -h
    usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
    Options and arguments (and corresponding environment variables):
    -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
             and comparing bytes/bytearray with str. (-bb: issue errors)
    [ ... complete help text not shown ... ]
    
    12 to provide flexibility in running your Python programs
  • Các thư viện tiêu chuẩn Python như
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    71 hoặc
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    99 đó là xử lý dòng lệnh trừu tượngPython standard libraries like
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    71 or
    $ ./main Python Command Line Arguments
    Arguments count: 5
    Argument      0: ./main
    Argument      1: Python
    Argument      2: Command
    Argument      3: Line
    Argument      4: Arguments
    
    99 that abstract command line processing
  • Các gói Python mạnh mẽ như
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    72 và
    C:/>main
    Arguments count: 1
    Argument      0: main
    
    50 để cải thiện hơn nữa khả năng sử dụng của các chương trình của bạnpowerful Python packages like
    $ gcc -o main main.c
    $ ./main
    Arguments count: 1
    Argument      0: ./main
    
    72 and
    C:/>main
    Arguments count: 1
    Argument      0: main
    
    50 to further improve the usability of your programs

Cho dù bạn đang chạy một tập lệnh nhỏ hoặc một ứng dụng dựa trên văn bản phức tạp, khi bạn hiển thị giao diện dòng lệnh, bạn sẽ cải thiện đáng kể trải nghiệm người dùng về phần mềm Python của mình. Trên thực tế, bạn có thể là một trong những người dùng đó!command line interface you’ll significantly improve the user experience of your Python software. In fact, you’re probably one of those users!

Lần tới khi bạn sử dụng ứng dụng của mình, bạn sẽ đánh giá cao tài liệu bạn đã cung cấp với tùy chọn

 1// main.c
 2#include 
 3
 4int main(int argc, char *argv[]) {
 5    printf("Arguments count: %d\n", argc);
 6    for (int i = 0; i < argc; i++) {
 7        printf("Argument %6d: %s\n", i, argv[i]);
 8    }
 9    return 0;
10}
75 hoặc thực tế là bạn có thể truyền các tùy chọn và đối số thay vì sửa đổi mã nguồn để cung cấp dữ liệu khác nhau.

Tài nguyên bổ sung

Để có được những hiểu biết sâu sắc hơn về các đối số dòng lệnh Python và nhiều khía cạnh của chúng, bạn có thể muốn kiểm tra các tài nguyên sau:

  • So sánh các thư viện phân tích cú pháp dòng lệnh Python-Argparse, Docopt và nhấp chuột
  • Python, Ruby và Golang: So sánh ứng dụng dòng lệnh

Bạn cũng có thể muốn thử các thư viện Python khác nhắm mục tiêu các vấn đề tương tự trong khi cung cấp cho bạn các giải pháp khác nhau:

  • Typer
  • Vị trí
  • Vách đá
  • Xi măng
  • Lửa Python

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để làm sâu sắc thêm sự hiểu biết của bạn: Giao diện dòng lệnh trong Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Command Line Interfaces in Python