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

Command Line Interface (CLI) ใน Python: สร้าง CLI ด้วย Click Library

Command Line Interface (CLI) เป็นโปรแกรมที่รันจาก terminal/shell โดยรับคำสั่งผ่าน arguments, options, flags Python มี library Click ช่วยสร้าง CLI ได้ง่าย สวย ตามหลัก DRY (Don't Repeat Yourself)

โครงสร้าง CLI

องค์ประกอบ คำอธิบาย ตัวอย่าง
Argumentsพารามิเตอร์บังคับ ต้องระบุpip install numpy → numpy คือ argument
Optionsพารามิเตอร์ตัวเลือก มีชื่อและค่า--cache-dir ./cache
FlagsOption แบบ boolean (เปิด/ปิด)--help, --verbose

ตัวอย่าง CLI แบบไม่ใช้ Click (Manual parsing)

import sys
import random

def do_work():
    args = sys.argv[1:]  # ข้าม script name
    
    if not args:
        print('You have not passed any commands!')
        return
    
    for a in args:
        if a == '--help':
            print('Basic command line program')
            print('Options:')
            print(' --help -> show this help menu.')
            print(' --monty -> show a Monty Python quote.')
            print(' --veg -> show a random vegetable')
        elif a == '--monty':
            print("He's not the Messiah—he's a very naughty boy")
        elif a == '--veg':
            print(random.choice(['Tomato', 'Radish', 'Carrot', 'Potato', 'Turnip']))
        else:
            print('Unrecognised argument.')

if __name__ == '__main__':
    do_work()

ผลลัพธ์:

$ python cli.py --monty
He's not the Messiah—he's a very naughty boy

$ python cli.py --help
Basic command line program
Options:
 --help -> show this basic help menu.
 --monty -> show a Monty Python quote.
 --veg -> show a random vegetable

$ python cli.py --veg
Tomato

ตัวอย่าง CLI ด้วย Click (แนะนำ)

import click
import random

@click.command()
@click.option('--monty', is_flag=True, help='Show a Monty Python quote.')
@click.option('--veg', is_flag=True, help='Show a random vegetable.')
def do_work(monty, veg):
    """Basic Click example will follow your commands"""
    if monty:
        print("He's not the Messiah—he's a very naughty boy")
    if veg:
        print(random.choice(['Tomato', 'Radish', 'Carrot', 'Potato', 'Turnip']))

if __name__ == '__main__':
    do_work()

ผลลัพธ์ --help อัตโนมัติ:

$ python cli_click.py --help
Usage: cli_click.py [OPTIONS]
Basic Click example will follow your commands

Options:
  --monty     Show a Monty Python quote.
  --veg       Show a random vegetable.
  --help      Show this message and exit.

คุณสมบัติเด่นของ Click

  • Auto-generated help จาก docstring และ help parameter
  • Type conversion อัตโนมัติ (string → int, float, Path, etc.)
  • Validation ค่าที่รับได้
  • Nested commands (subcommands) เช่น git commit, git push
  • Context passing ระหว่าง commands
  • Prompts ขอ input จากผู้ใช้แบบ interactive

ตัวอย่าง Click ขั้นสูง: Arguments, Types, Validation

import click

@click.command()
@click.argument('name')
@click.option('--count', default=1, type=int, help='Number of greetings.')
@click.option('--greeting', type=click.Choice(['Hello', 'Hi', 'Hey']), default='Hello')
def greet(name, count, greeting):
    """Greet NAME COUNT times with GREETING."""
    for _ in range(count):
        click.echo(f"{greeting}, {name}!")

if __name__ == '__main__':
    greet()

การใช้งาน:

$ python greet.py World --count 3 --greeting Hi
Hi, World!
Hi, World!
Hi, World!

$ python greet.py --help
Usage: greet.py [OPTIONS] NAME
Greet NAME COUNT times with GREETING.

Options:
  --count INTEGER   Number of greetings.
  --greeting CHOICE Greeting type.
  --help            Show this message and exit.

ติดตั้ง Click

pip install click

Libraries CLI อื่นๆ ที่น่าสนใจ

Library คุณสมบัติเด่น
ClickSimple, decorator-based, auto-help, นิยมมาก
TyperBuilt on Click, ใช้ type hints, รองรับ async
argparseStandard library, ไม่ต้องติดตั้งเพิ่ม
FireAuto-generate CLI จาก object/function ใดๆ
CliffFramework สำหรับ CLI ที่ซับซ้อน (multi-command)

สรุป

  • Click ทำให้เขียน CLI เร็ว สะอาด มี help อัตโนมัติ
  • ใช้ @click.command() + @click.option() + @click.argument()
  • เหมาะสำหรับ CLI tools, scripts, DevOps automation