Topic 25 of 64
Execution via CLI Scripts
Overview
Running Python scripts from the command line is the foundational skill for automation, scripting, and building tools. Understanding sys.argv and script entry points prepares you for real automation work.
Syntax
python
# Run a script
python3 script.py
# Pass arguments
python3 script.py arg1 arg2
# Access arguments inside script
import sys
print(sys.argv) # ['script.py', 'arg1', 'arg2']
print(sys.argv[1]) # 'arg1'Common Pitfalls
- sys.argv[0] is always the script filename itself — user arguments start at index 1.
- For complex CLIs, use the 'argparse' module for named flags, defaults, and help messages.
- Interview tip: Know the difference between running as a script vs importing — 'if __name__ == "__main__":' guards entry point logic.
Real-World Example
A CLI script that greets a user by name passed as an argument
example
python
import sys
if len(sys.argv) < 2:
print("Usage: python3 greet.py <name>")
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}!")
# Run: python3 greet.py Alice → Hello, Alice!