If you want to create a Python program that can be executed from the command line, I think it is common to use ʻargparse or ʻoptparse
to process the command line arguments.
Using the Click library is convenient because you can easily create a console application simply by wrapping an arbitrary function with a decorator.
Let's try a simple implementation to get the URL.
http_fetcher.py
import click
import requests
@click.command()
@click.argument('url')
def fetch(url):
click.echo(requests.get(url).text.encode('utf-8'))
if __name__ == '__main__':
fetch()
% python http_fetcher.py http://www.qiita.com/
<!DOCTYPE html>...
If you specify an argument with * -o *, it will be written to the file.
http_fetcher2.py
import click
import requests
import sys
@click.command()
@click.argument('url')
@click.option('-o', '--out-file', type=click.File('w'))
def fetch(url, out_file):
if not out_file:
out_file = sys.stdout
click.echo(requests.get(url).text.encode('utf-8'), file=out_file)
if __name__ == '__main__':
fetch()
% python http_fetcher2.py -o index.html http://qiita.com
% cat index.html
<!DOCTYPE html>...
The file is also convenient because Click automatically opens it and returns it as a File Object.
There are many other nice features such as command grouping and progress bar display. The documentation is here.
Recommended Posts