What to do:
-
Install Python 3.8+ from python.org.
-
Create a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
Example:
Your shell prompt should show (venv) when activated.
What to do:
-
Write a script that accepts arguments:
import argparse
parser = argparse.ArgumentParser(description='Greet the user.')
parser.add_argument('--name', required=True, help='Your name')
args = parser.parse_args()
print(f'Hello, {args.name}!')
Example:
Run python greet.py --name Alice to see the greeting.
What to do:
-
Add subcommands for different actions:
parser = argparse.ArgumentParser(description='Todo CLI')
subparsers = parser.add_subparsers(dest='command')
add_parser = subparsers.add_parser('add', help='Add a todo')
add_parser.add_argument('task')
list_parser = subparsers.add_parser('list', help='List todos')
args = parser.parse_args()
if args.command == 'add':
print(f'Added: {args.task}')
elif args.command == 'list':
print('Listing todos...')
Example:
Try python todo.py add "Buy milk" and python todo.py list.
What to do:
-
Install click:
-
Create a click-based CLI:
import click
@click.group()
def cli():
pass
@cli.command()
def hello():
click.echo('Hello from click!')
if __name__ == '__main__':
cli()
Example:
Run python cli.py hello to see the output.
What to do:
-
Use click's color features:
@cli.command()
def warn():
click.secho('Warning!', fg='yellow', bold=True)
Example:
The warning message appears in yellow and bold.
What to do:
-
Add a setup.py file:
from setuptools import setup
setup(
name='mycli',
py_modules=['cli'],
install_requires=['click'],
entry_points='''
[console_scripts]
mycli=cli:cli
''',
)
-
Install your CLI locally:
Example:
Now you can run mycli hello from anywhere.
What to do:
-
Write tests using pytest:
def test_hello(runner):
result = runner.invoke(cli, ['hello'])
assert 'Hello' in result.output
-
Add a README.md with usage examples.
Example:
A good README and tests make your project stand out on GitHub.