Python Command Line Tool Example
A command line tool is a Python script that you run from the terminal and give input to when the script starts.
This beginner-friendly example shows:
- how to build a small Python CLI tool
- how to read command line arguments with
sys.argv - how to handle missing or invalid input
- how to run the script from the terminal
If you are new to this, the main idea is simple: the user runs a file like python tool.py Alice, and your script uses Alice as input.
Quick example #
Use this as the smallest possible command line tool example.
Save it as tool.py:
import sys
if len(sys.argv) < 2:
print("Usage: python tool.py NAME")
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}!")
Run it like this:
python tool.py Alice
Expected output:
Hello, Alice!
This example teaches the basic pattern:
- import
sys - check whether an argument exists
- read the argument
- print a result
What this example builds #
This page builds a very small script that runs from the terminal.
It shows how to:
- run a Python file from the command line
- pass input as command line arguments
- check whether the user gave enough input
- print a useful result
The goal is to help you understand the basic pattern of a command line tool before moving on to more advanced tools like argparse.
When to use a command line tool #
A command line tool is useful when:
- you want to run a task quickly without editing the code
- the script should accept different values each time
- you want to automate a small task
- you are working with files, text, or simple calculations
This is a good first step before learning full argument parsers.
How command line arguments work #
Python stores command line arguments in sys.argv.
sys.argv is a list:
sys.argv[0]is the script filenamesys.argv[1]is the first value given by the usersys.argv[2]is the second value, and so on
For example, if you run:
python tool.py Alice
then sys.argv looks like this:
['tool.py', 'Alice']
If you run:
python tool.py 3 5
then sys.argv looks like this:
['tool.py', '3', '5']
Notice that command line values are strings. If you need numbers, you must convert them. You can learn more on the int() function explained page.
Build the first working version #
Start with this script:
import sys
if len(sys.argv) < 2:
print("Usage: python tool.py NAME")
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}!")
What each part does #
import sys
- gives your script access to
sys.argv
if len(sys.argv) < 2:
- checks whether the user gave at least one real argument
- remember:
sys.argv[0]is only the filename
print("Usage: python tool.py NAME")
- shows the user how to run the script correctly
sys.exit(1)
- stops the program because the input is missing
name = sys.argv[1]
- reads the first user argument
print(f"Hello, {name}!")
- prints the result using an f-string
If you want to review printing output, see print() explained.
Improve the tool with a real task #
A greeting example is useful for learning, but a real tool often does a task.
Here is a second example that adds two numbers.
Save this as add_tool.py:
import sys
if len(sys.argv) < 3:
print("Usage: python add_tool.py NUMBER1 NUMBER2")
sys.exit(1)
try:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
except ValueError:
print("Error: both arguments must be whole numbers.")
sys.exit(1)
total = num1 + num2
print(f"Result: {total}")
How this version works #
This script adds two improvements:
- it expects two arguments instead of one
- it handles bad input with
tryandexcept
Example runs #
Correct input:
python add_tool.py 3 5
Output:
Result: 8
Missing input:
python add_tool.py 3
Output:
Usage: python add_tool.py NUMBER1 NUMBER2
Invalid input:
python add_tool.py 3 hello
Output:
Error: both arguments must be whole numbers.
This is an important beginner pattern:
- check the number of arguments
- convert values if needed
- handle possible errors clearly
If you want more help with this part, see how to handle exceptions in Python and Python errors and exceptions explained.
How to run the script #
Follow these steps:
- Save the script in a file ending with
.py - Open a terminal in the same folder
- Run the script with
python filename.py arguments
Example commands #
For the greeting tool:
python tool.py Alice
Expected output:
Hello, Alice!
For the add tool:
python add_tool.py 3 5
Expected output:
Result: 8
Useful terminal commands #
These commands can help when testing:
python tool.py
python tool.py Alice
python tool.py 3 5
python -V
pwd
cd path/to/script/folder
ls
dir
Notes:
python -Vshows your Python versionpwdshows your current folder on macOS and Linuxlslists files on macOS and Linuxdirlists files on Windowscdchanges to the folder that contains your script
Common beginner mistakes #
Here are some common problems when building a Python command line tool.
Forgetting that arguments are strings #
If you run:
python add_tool.py 3 5
the values "3" and "5" start as strings, not numbers.
That is why this fails to do numeric work unless you convert them:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
Using sys.argv[1] without checking length first #
This is a common cause of IndexError.
Bad example:
import sys
name = sys.argv[1]
print(name)
If no argument is given, the script crashes.
Safer version:
import sys
if len(sys.argv) < 2:
print("Usage: python tool.py NAME")
sys.exit(1)
name = sys.argv[1]
print(name)
Running the script from the wrong folder #
If the terminal is not in the same folder as your file, Python may not find the script.
Use:
pwd
ls
dir
cd path/to/script/folder
to check where you are and move to the correct folder.
Misspelling the filename or command #
Make sure:
- the filename is correct
- the extension is
.py - you use the correct Python command for your system
Next steps after this example #
After this example, a good path is:
- learn
sys.argvin more detail - read how to use command line arguments in Python
- practice
try/excepterror handling - move on to
argparsefor better command line tools
A good exercise is to copy one of the scripts from this page and extend it into:
- a mini calculator
- a text formatter
- a simple file-based tool
FAQ #
What is a command line tool in Python? #
It is a Python script that you run from the terminal and give input through command line arguments.
What is sys.argv? #
It is a list of values passed to the script from the command line. The first item is the script name.
Why does my script fail when no argument is given? #
You are probably reading sys.argv[1] before checking that the user actually passed an argument.
Can I use input() instead of sys.argv? #
Yes, but input() asks during program execution. sys.argv lets you pass values when starting the script.
What should I learn after this? #
Learn sys.argv first, then argparse, plus basic error handling with try-except.