Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การจัดการอาร์กิวเมนต์บรรทัดคำสั่งใน Python (Argument Parsing)

เมื่อรันสคริปต์ Python จากเทอร์มินัล มักต้องส่งอาร์กิวเมนต์เข้าไป บทความนี้เปรียบเทียบ 3 วิธีหลัก: sys.argv, getopt, และ argparse

1. ใช้ sys.argv (พื้นฐานที่สุด)

sys.argv[0] คือชื่อไฟล์ ส่วน sys.argv[1] ขึ้นไปคืออาร์กิวเมนต์ที่ส่งมา

ตัวอย่าง

import sys
print(sys.argv[0])
print("Hello ", sys.argv[1], ", welcome!")

การรันและผลลัพธ์

D:\Pythons\py3projects> python3 args_demo.py Samantha
args_demo.py
Hello Samantha, welcome!

2. ใช้ getopt (ยืดหยุ่นกว่า)

รองรับออปชันแบบยาว/สั้น มีการจัดการข้อผิดพลาดพื้นฐาน

ตัวอย่าง

import getopt
import sys

all_args = sys.argv[1:]
prod = 1
try:
    opts, args = getopt.getopt(all_args, 'x:y:')
    if len(opts) != 2:
        print('usage: args_demo.py -x  -y ')
    else:
        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)

ผลลัพธ์

D:\Pythons\py3projects> python3 args_demo.py -x 3 -y 12
Product of the two numbers is 36

D:\Pythons\py3projects> python3 args_demo.py
usage: args_demo.py -x  -y 

3. ใช้ argparse (แนะนำมากที่สุด)

จัดการข้อผิดพลาด อัตโนมัติ สร้าง help message เองได้ รองรับ type checking และ required fields

ตัวอย่าง

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-x", "--Value1", required=True, help="first Value")
parser.add_argument("-y", "--Value2", required=True, help="second Value")
args = vars(parser.parse_args())

print("Product is {}".format(int(args['Value1']) * int(args['Value2'])))

ผลลัพธ์

D:\Pythons\py3projects> python3 args_demo.py -x 3 -y 21
Product is 63

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

สรุป: argparse เป็นมาตรฐานปัจจุบัน สำหรับ CLI จริงควรใช้ตัวนี้ sys.argv ใช้ได้เฉพาะกรณีง่ายๆ getopt เป็นทางเลือกกลาง