This tutorial was written in 2019. Python and library APIs may need changes to run these examples today.
The previous post built a command-line program with argparse. This post uses Click, which provides decorators for defining commands and options.
Click
python -m pip install click requests beautifulsoup4
Create the equivalent greeting program in a package named cello:
# cello/main.py
import click
import sys
def say_hello(name):
click.echo("Hello, {}".format(name))
def say_goodbye(name):
click.echo('Good bye, {}'.format(name))
@click.option('--bye', is_flag=True, help="say good bye.")
@click.option('--hello', is_flag=True, help="say hello.")
@click.option('-v', '--version', is_flag=True, help="Show version of this program.")
@click.argument('name')
@click.command()
def main(name, version, hello, bye):
if version:
print('1.0.0')
sys.exit()
if bye:
say_goodbye(name)
else:
say_hello(name)
if __name__ == "__main__":
main()
$ python main.py --help
>>
Usage: main.py [OPTIONS] NAME
Options:
-v, --version Show version of this program.
--hello say hello.
--bye say good bye.
--help Show this message and exit.
$ python main.py sjquant --hello
>> Hello, sjquant
$ python main.py sjquant --bye
>> Good bye, sjquant
Define a console entry point in setup.py, install the package, and invoke the cello command:
# setup.py
from setuptools import setup, find_packages
setup(
name='cello',
version='1.0.0',
author='SJQuant',
author_email='seonujang92@gmail.com',
description='Greet someone',
packages=find_packages(),
entry_points={
"console_scripts": [
"cello = cello.main:main"
]
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
)
$ python -m pip install .
$ cello sjquant --bye
>> Good bye, sjquant
Command groups
click.group can collect multiple commands. The original example defines a CLI that looks up meanings and examples in Naver Dictionary. Focus on the Click decorators and main if you prefer to skip the scraping details. The external website and its markup may have changed since this example was written.
ndict/
├── setup.py
└── ndict/
├── __init__.py
└── main.py
# ndict/main.py
import click
import requests
from bs4 import BeautifulSoup
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
"""
Simple CLI for crawling Naver Dictionary
"""
pass
def search_meaining(word, url):
"""
search meaning from given url
Params
----------
word: str
url: str
"""
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
try:
word_box = soup.select('.word_num .list_e2')[0]
except IndexError:
import sys
click.echo('No results for "{}".'.format(word))
sys.exit()
info = word_box.find('dd').find('p')
if info.find('span')['class'][0] == 'fnt_k05':
word_class = None
else:
word_class = word_box.select('dd p .fnt_k09')[0].text
meaning = word_box.select('dd p .fnt_k05')[0].text
try:
example = word_box.select('dd p .fnt_e07._ttsText')[0].text
except IndexError:
example = None
click.echo('Search results for "{}"'.format(word))
click.echo('='*80)
if word_class:
click.echo('Part of speech: {}'.format(word_class))
click.echo('Meaning: {}'.format(meaning))
if example:
click.echo('Example: {}'.format(example))
def search_example(word, url):
"""
search example from given url
Params
----------
word: str
url: str
"""
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
try:
word_box = soup.select('.word_num .list_a')[0]
except IndexError:
import sys
click.echo('No results for "{}".'.format(word))
sys.exit()
examples_eng = word_box.select('.fnt_e09._ttsText')
examples_kr = word_box.select('div.fnt_k10')
click.echo('Search results for "{}"'.format(word))
click.echo('='*80)
index = 1
for eng, kr in zip(examples_eng, examples_kr):
click.echo(index)
click.echo(eng.text)
click.echo(kr.text)
index += 1
@click.command(help="This searches and returns meaning of a word from Naver Dictionary")
@click.argument('word')
@click.option('-e', '--english-only', is_flag=True, help="Show english version of meaning")
def meaning(word, english_only):
"""
This searches and returns meaning of a word from Naver Dictionary
Params
----------
word: str
word to search
english_only: bool
if True, search only english version of meaning
"""
if english_only:
url = 'https://endic.naver.com/search.nhn?sLn=kr&query={}&searchOption=all&isOnlyViewEE=Y'.format(
word)
else:
url = "https://endic.naver.com/search.nhn?sLn=kr&searchOption=all&query={}".format(
word)
search_meaining(word, url)
@click.command(help="This searches and returns examples of a word from Naver Dictionary")
@click.argument('word')
def example(word):
"""
This searches and returns examples of a word from Naver Dictionary
Params
----------
word: str
word to search
"""
url = "https://endic.naver.com/search.nhn?sLn=kr&searchOption=all&query={}".format(
word)
search_example(word, url)
def main():
cli.add_command(meaning)
cli.add_command(example)
cli()
if __name__ == "__main__":
main()
Add the entry point:
# setup.py
from setuptools import setup, find_packages
setup(
name='ndict',
version='1.0.0',
author='SJQuant',
author_email='seonujang92@gmail.com',
description='Simple CLI for crawling Naver Dictionary',
packages=find_packages(),
entry_points={
"console_scripts": [
"ndict = ndict.main:main"
]
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
)
The original post recorded these help and output examples. The dictionary returns Korean definitions and translations:
$ ndict --help
Usage: ndict [OPTIONS] COMMAND [ARGS]...
Simple CLI for crawling Naver Dictionary
Options:
-h, --help Show this message and exit.
Commands:
example This searches and returns examples of a word from Naver Dictionary
meaning This searches and returns meaning of a word from Naver Dictionary
$ ndict meaning --help
Usage: ndict meaning [OPTIONS] WORD
This searches and returns meaning of a word from Naver Dictionary
Options:
-e, --english-only Show english version of meaning
-h, --help Show this message and exit.
$ ndict meaning program
>>
Search results for "program"
================================================================================
Part of speech: [명사]
Meaning: 프로그램
Example: Load the program into the computer.
$ ndict example program
>>
Search results for "program"
================================================================================
1
Displays program information , version number , and copyright .
프로그램 정보, 버전 번호, 저작권을 표시합니다.
2
Tom turned in to documentary program for his report .
탐은 그의 리포트를 위해서 다큐멘터리 프로그램에 채널을 맞추었다.
3
This program is allowed for children above 8 years old .
이 프로그램은 8세 이상의 어린이에게만 허용된다.
4
The news program was bitten off .
뉴스 프로그램은 잘렸다.
5
This program is sponsored by B publishing company .
이 프로그램은 B출판사 제공이었습니다
See the Click documentation for more information.