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ườngsys.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ểm | getopt | argparse |
|---|---|---|
| Độ phức tạp | Thấp | Cao |
| Tự động generate help | Không | Có |
| Type checking | Không | Có (int, float, file, v.v.) |
| Subcommand | Không | Có |
| Validation | Manual | Built-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ũ.