Skip to main content

命令行 Command line

import sys
print(sys.argv)
python mainpy beau 39

# echo: ["main.py", "beau", "39"]

build command with argparse

import argparse

parser = argparse.ArgumentParser(description="This program prints the name of my dogs")

parser.add_argument("-c", "--color", metavar="color", required=True, choices={"red", "yellow"}, help="the color to search for")

args = parse.parse_args()

print(args.color)

build command with click

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo(f"Hello {name}!")

if __name__ == '__main__':
hello()
python hello.py --count=3
Your name: John
Hello John!
Hello John!
Hello John!