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

C-style Parser สำหรับ Command Line Options ใน Python (getopt)

โมดูล sys ของ Python ให้เข้าถึง Command-line Arguments ผ่าน sys.argv ซึ่ง sys.argv[0] คือชื่อสคริปต์

โมดูล getopt

มีฟังก์ชัน Parse Command Line Arguments ใน sys.argv รองรับ Convention เดียวกับ Unix getopt() รวมถึงความหมายพิเศษของ - และ -- API ออกแบบให้คุ้นเคยกับผู้ใช้ C getopt()

getopt(args, shortopts, longopts=[])

  • args: รายการอาร์กิวเมนต์ ไม่รวม sys.argv[0] (ปกติคือ sys.argv[1:])
  • shortopts: สตริงตัวอักษร Option ที่ Script จะรู้จัก Option ที่ต้องการ Argument ตามด้วย Colon (:)
  • longopts: รายการ String ชื่อ Long Options (ไม่ต้องใส่ -- นำหน้า) Long Option ที่ต้องการ Argument ตามด้วย Equal Sign (=)

คืนค่า 2 ส่วน: 1) รายการ (option, value) pairs 2) รายการ Program Arguments ที่เหลือหลัง Strip Options แล้ว

ตัวอย่าง

import sys, getopt

def main():
    input_file = ''
    output_file = ''
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        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"):
            input_file = arg
        elif opt in ("-o", "--ofile"):
            output_file = arg
    
    print('Input file is:', input_file)
    print('Output file is:', output_file)

if __name__ == "__main__":
    main()

ผลลัพธ์ตัวอย่าง

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

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

หมายเหตุ: Python 3.2+ แนะนำให้ใช้โมดูล argparse แทน ซึ่งทรงพลังและใช้ง่ายกว่า