Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Parser dòng lệnh kiểu C trong Python (getopt)

Module sys cung cấp sys.argv (danh sách tham số dòng lệnh). Module getopt parse theo quy ước Unix getopt() (hỗ trợ short option -x và long option --long).

sys.argv cơ bản

import sys
print('Argument list:', sys.argv)
# python args.py 11 22 -> ['args.py', '11', '22']

getopt.getopt(args, shortopts, longopts=[])

  • args: Danh sách tham số (thường sys.argv[1:]).
  • shortopts: Chuỗi ký tự option, option có tham số theo sau : (ví dụ "hi:o:").
  • longopts: List tên long option (không có --), option có tham số theo sau = (ví dụ ["ifile=", "ofile="]).

Trả về

Tuple (opts, args):

  • opts: List cặp (option, value). Option có prefix - (short) hoặc -- (long).
  • args: Danh sách tham số còn lại sau khi strip options.

Ví dụ hoàn chỉnh

import sys, getopt

def main():
    inputfile = ''
    outputfile = ''
    args = sys.argv[1:]
    
    try:
        opts, args = getopt.getopt(args, "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError as err:
        print(f'Error: {err}')
        print('Usage: test.py -i  -o ')
        sys.exit(2)
    
    for opt, arg in opts:
        if opt == '-h':
            print('Usage: test.py -i  -o ')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    
    print(f'Input file: "{inputfile}"')
    print(f'Output file: "{outputfile}"')

if __name__ == '__main__':
    main()

Chạy thử

$ python args.py -h
Usage: test.py -i  -o 

$ python args.py -i abc.txt -o xyz.txt
Input file: "abc.txt"
Output file: "xyz.txt"

$ python args.py --ifile=abc.txt --ofile=xyz.txt
Input file: "abc.txt"
Output file: "xyz.txt"

So sánh với argparse (khuyên dùng cho project thực tế)

Đặc điểmgetoptargparse
Độ phức tạpThấpCao
Tự động generate helpKhôngCó
Type checkingKhôngCó (int, float, file, v.v.)
SubcommandKhôngCó
ValidationManualBuilt-in

Khuyến nghị: Dùng argparse cho CLI chính thức; getopt cho script nhanh, đơn giản hoặc tương thích code cũ.