Click 사용법
예제
1. click_test1.py
import click
@click.command()
@click.argument('name')
def main(name):
print(f'Hello {name}!')
if __name__ == '__main__':
main()
2. click_test2.py
import click
@click.command()
@click.argument('name')
@click.option('--number', type=int)
def main(name, number):
for i in range(number):
print(f'Hello {name}!')
if __name__ == '__main__':
main()
Help message도 자유롭게 작성가능
3. click_test3.py
import click
@click.command()
@click.argument('name')
@click.option('--number', type=int, help='Help message here')
def main(name, number):
'''
help message for user
'''
for i in range(number):
print(f'Hello {name}!')
if __name__ == '__main__':
main()
click.Choice
weather.py
import click
@click.command()
@click.option('--weather', type=click.Choice(['sunny', 'rainy', 'snowy']))
def main(weather):
print(f'i love it when the weater is {weather}')
pass
if __name__ == "__main__":
main()
click.group
restaurant.py
import click
@click.group()
def cli():
pass
@cli.group()
def lunch():
pass
@cli.group()
def dinner():
pass
@click.command()
def burger():
print(f'Enjoy your burger!')
lunch.add_command(burger)
dinner.add_command(burger)
if __name__ == "__main__":
cli()
- group 따로 사용하기
import click
@click.group()
def cli():
pass
@cli.group()
def lunch():
pass
@cli.group()
def dinner():
pass
@lunch.command()
def burger():
print(f'Enjoy your lunch burger!')
@dinner.command()
def burger():
print(f'Enjoy your dinner burger!')
#@click.command()
#def burger():
# print(f'Enjoy your burger!')
# lunch.add_command(burger)
# dinner.add_command(burger)
if __name__ == "__main__":
cli()
%python
import sys
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."""
with open('echo.txt', 'w') as fobj:
for x in range(count):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
# first element is the script name, use empty string instead
sys.argv = ['', '--name', 'Max', '--count', '3']
hello()
댓글남기기