Python Course
Python provides built-in support for reading command-line arguments through modules like sys and argparse. This is critical for building scripts and applications that can accept user input from the terminal or shell.
What Are Command Line Arguments?
Command line arguments are values passed to a Python script when it is run from the command line. These arguments allow the script to behave differently depending on the input provided.
python greet.py Praveen
Here, Praveen is a command-line argument passed to the script greet.py.
Using sys.argv
Let's learn to access and manipulate basic command-line inputs.
import sys print("Script name:", sys.argv[0]) print("Arguments:", sys.argv[1:])
If you see here,
sys.argvis a list containing thescript nameand all arguments passed to the script.sys.argv[0]is always thescript name.- Remaining elements are arguments.
Let's see an example,
# greet.py import sys # Using Sys module to get command line arguments print("Hello, "+ sys.argv[1] + "!")
Let's execute the program,
python greet.py Praveen
Using the argparse Module
For more complex command-line interfaces, argparse is preferred.
Key Features of argparse:
- Positional arguments
- Optional arguments with flags (e.g.
--output) - Automatic help documentation
Let's see an example,
# greet.py import argparse # Using Argparse module to get command line arguments # This is more robust and user-friendly parser = argparse.ArgumentParser(description="Greet Name.") parser.add_argument("--name", type=str, required=True, help="The name to greet") args = parser.parse_args() print("Hello, " + args.name + "!")
Let's execute the program,
python greet.py --name=Praveen
Optional Arguments
parser.add_argument("--verbose", action="store_true", help="Increase output verbosity")
Let's see another example,
import argparse parser = argparse.ArgumentParser(description="Simple CLI Calculator") parser.add_argument("a", type=float, help="First number") parser.add_argument("b", type=float, help="Second number") parser.add_argument("--operation", choices=["add", "sub", "mul", "div"], required=True) args = parser.parse_args() if args.operation == "add": result = args.a + args.b elif args.operation == "sub": result = args.a - args.b elif args.operation == "mul": result = args.a * args.b elif args.operation == "div": result = args.a / args.b print(f"Result: {result}")
Creating Modules and Packages in Python
What is a Module?
A module is any .py file containing Python definitions, functions, and classes.
# math_utils.py def square(x): return x * x
We can import this module:
import math_utils print(math_utils.square(4))
What is a Package?
A package is a directory that contains a special file __init__.py and one or more modules.
Example Structure:
myapp/ ├── main.py └── utils/ ├── __init__.py └── math_utils.py
Usage in main.py:
from utils import math_utils print(math_utils.square(5))
The init.py File
- Marks a directory as a Python package.
- Can be empty, or expose selected modules/functions.
# utils/__init__.py from .math_utils import square
Now we can use:
from utils import square
Absolute vs Relative Imports
Absolute:
from utils.math_utils import square
Relative (inside another module in the same package):
from .math_utils import square
Creating a Reusable Package
Let’s build a package string_utils.
string_utils/ ├── __init__.py ├── formatter.py └── validator.py
formatter.py:
def to_uppercase(text): return text.upper()
validator.py:
def is_alpha(text): return text.isalpha()
init.py:
from .formatter import to_uppercase from .validator import is_alpha
Usage:
from string_utils import to_uppercase, is_alpha