Mọi ngôn ngữ lập trình đều có tính năng tạo script và chạy từ terminal hoặc được gọi bởi chương trình khác. Khi chạy script, thường cần truyền đối số cho các hàm bên trong. Bài viết này giới thiệu các cách truyền đối số vào script Python.
Sử dụng sys.argv
Module built-in sys.argv xử lý đối số truyền kèm script. Mặc định đối số đầu tiên sys.argv[0] là tên file, các đối số tiếp theo có chỉ mục 1, 2, ...
Ví dụ
import sys
print(sys.argv[0])
print("Hello", sys.argv[1], "welcome!")
Chạy script từ terminal:
D:\Pythons\py3projects>python3 args_demo.py Samantha args_demo.py Hello Samantha welcome!
Sử dụng getopt
getopt linh hoạt hơn, cho phép thu thập giá trị đối số, xử lý lỗi và ngoại lệ. Ví dụ dưới tìm tích hai số bằng cách lấy đối số, bỏ qua tên file.
Ví dụ
import getopt
import sys
# Bỏ đối số đầu tiên (tên file)
all_args = sys.argv[1:]
prod = 1
try:
# Thu thập đối số
opts, arg = getopt.getopt(all_args, 'x:y:')
# Phải có đúng hai tùy chọn
if len(opts) != 2:
print('usage: args_demo.py -x -y ')
else:
# Duyệt qua tùy chọn và giá trị
for opt, arg_val in opts:
prod *= int(arg_val)
print('Product of the two numbers is {}'.format(prod))
except getopt.GetoptError:
print('usage: args_demo.py -x -y ')
sys.exit(2)
Kết quả
D:\Pythons\py3projects>python3 args_demo.py -x 3 -y 12 Product of the two numbers is 36 # Lần chạy tiếp D:\Pythons\py3projects>python3 args_demo.py usage: args_demo.py -x-y
Sử dụng argparse
argparse là module được khuyến nghị nhất vì tự xử lý lỗi/ngoại lệ mà không cần code thêm. Khai báo tên, help text cho mỗi đối số, sau đó dùng tên đối số trong code.
Ví dụ
import argparse
# Tạo parser
all_args = argparse.ArgumentParser()
# Thêm đối số
all_args.add_argument("-x", "--Value1", required=True, help="first Value")
all_args.add_argument("-y", "--Value2", required=True, help="second Value")
args = vars(all_args.parse_args())
# Tính tích
print("Product is {}".format(int(args['Value1']) * int(args['Value2'])))
Kết quả
D:\Pythons\py3projects>python3 args_demo.py -x 3 -y 21 Product is 63 # Lần chạy tiếp D:\Pythons\py3projects>python3 args_demo.py -x 3 -y usage: args_demo.py [-h] -x VALUE1 -y VALUE2 args_demo.py: error: argument -y/--Value2: expected one argument