Writing Command-Line Programs
Python automatically collects all command-line arguments and stores them in a special variable called sys.argv, which is a list of strings. Your program can read and use these arguments to control its behavior.
What Command-Line Arguments Are
When you run a program from the terminal or command prompt, you can pass information to it directly on the command line. For example, if you type python my_program.py hello world, you are running my_program.py and passing hello and world as arguments to that program. Command-line arguments let your program receive input without requiring the user to type responses interactively after the program starts. This is especially useful for scripts that process files, configure behavior, or chain together with other programs.
Python automatically collects all command-line arguments and stores them in a special variable called sys.argv, which is a list of strings. Your program can read and use these arguments to control its behavior.
Accessing Arguments with sys.argv
The sys.argv variable is a list of strings that contains the command-line arguments passed to your program. The first element, sys.argv[0], is always the name of the script itself. The remaining elements, sys.argv[1], sys.argv[2], and so on, are the arguments you typed after the program name. For instance, if you run python greet.py Alice Bob, then sys.argv[0] is 'greet.py', sys.argv[1] is 'Alice', and sys.argv[2] is 'Bob'. To use sys.argv in your program, you must first import the sys module at the top of your file.
A Simple Greeting Program
Write a program that accepts a name as a command-line argument and prints a personalized greeting.
- 1Import the sys module
At the top of your program, write import sys so you can access
sys.argv. - 2Check the number of arguments
Use
len(sys.argv)to determine how many arguments were passed. If the user provided a name,len(sys.argv)will be 2 (the script name plus one argument). - 3Extract and use the argument
Access
sys.argv[1] to get the name the user provided, then print a greeting that includes that name. - 4Run from the command line
Execute the program by typing python
greet.pyAlice at the command prompt. The program receives 'Alice' assys.argv[1] and prints the greeting.
When you run python greet.py Alice, the program outputs: Hello, Alice! Welcome to our program.
Single Logical Line Per Physical Line
Python allows you to write multiple logical statements on a single physical line by separating them with semicolons. However, this practice is strongly discouraged. The recommended convention is to write a maximum of one logical line on each physical line of code. A logical line is a complete Python statement, such as an assignment, a function call, or a control structure. A physical line is what you see on your screen—each line that ends when you press Enter. By keeping one logical line per physical line, your code becomes much easier to read, debug, and maintain. In fact, experienced Python programmers rarely use semicolons in their code at all.
Always write one logical line per physical line. Never use semicolons to combine multiple statements on a single line. This makes your code clearer, easier to step through with a debugger, and simpler for other programmers (and your future self) to understand at a glance.
Common Mistakes When Writing Command-Line Programs
Common mistake Forgetting to import sys before using sys.argv
What it looks likeRunning a program that uses sys.argv without import sys at the top
Why it failsPython will raise a
NameErrorbecause sys is not defined in your program's namespace.Do this insteadAlways include import sys at the beginning of any program that accesses command-line arguments.
Common mistake Assuming sys.argv[1] exists without checking the argument count
What it looks likeWriting code like name = sys.argv[1] without first verifying that the user provided an argument
Why it failsIf the user runs the program without arguments,
sys.argvwill only contain the script name, and accessingsys.argv[1] will raise anIndexError.Do this insteadCheck len(sys.argv) before accessing specific indices, or use a try-except block to handle missing arguments gracefully.
Common mistake Using semicolons to put multiple statements on one line
What it looks likeWriting x = 5; y = 10; print(x + y) instead of putting each statement on its own line
Why it failsWhile Python allows this, it violates the single logical line per physical line convention and makes code harder to read and debug.
Do this insteadWrite each statement on a separate physical line without semicolons.
Common mistake Forgetting that sys.argv contains strings, not other data types
What it looks likeRunning python calculate.py 5 10 and then trying to add sys.argv[1] + sys.argv[2] expecting the result to be 15
Why it failssys.argv[1] andsys.argv[2] are the strings '5' and '10', so adding them produces '510', not 15.Do this insteadConvert command-line arguments to the appropriate type using int(), float(), or other conversion functions before performing operations on them.
Writing a Complete Command-Line Program
Let's trace through a complete example that demonstrates both proper command-line argument handling and the single logical line per physical line convention. This program will calculate the sum of two numbers passed as command-line arguments.
When run as: python add.py 7.5 3.2
The sum of 7.5 and 3.2 is 10.7- 1Line 1: Import the sys module to access
sys.argv. - 2Line 3: Check if exactly 3 elements are in
sys.argv(the script name plus two arguments). - 3Line 4: If not, print a usage message showing the user how to run the program correctly.
- 4Line 5: Exit the program with error code 1 to indicate failure.
- 5Line 7: Convert the first command-line argument from a string to a float.
- 6Line 8: Convert the second command-line argument from a string to a float.
- 7Line 9: Calculate the sum of the two numbers.
- 8Line 11: Print the result in a formatted string. Notice that each logical statement is on its own physical line—no semicolons are used.
This program demonstrates three key practices: importing sys, checking argument count before accessing specific indices, and converting string arguments to the appropriate numeric type. Each statement occupies its own line, making the logic clear and easy to follow.
Why Python Differs from Other Languages
Many programming languages, such as C, Java, and JavaScript, require semicolons at the end of every statement. These languages use the semicolon as the statement terminator, so you can write multiple statements on one line and the language will still parse them correctly. Python takes a different approach: it uses the newline character as the statement terminator. In Python, a new line typically means a new statement, so semicolons are unnecessary. While Python does support semicolons for backward compatibility and for rare cases where you need to separate multiple statements on one line, the language's design philosophy encourages writing one logical line per physical line. This design choice makes Python code more readable and less prone to certain formatting errors.
| Language | Statement Terminator | Multiple Statements Per Line | Python Convention |
|---|---|---|---|
| Python | Newline (implicit) | Possible with semicolon, but discouraged | One logical line per physical line |
| C / Java / JavaScript | Semicolon (required) | Common and expected | Not applicable |
How different languages handle statement termination and line structure
Practice: Build Your Own Argument Handler
Write a Python program called greet_user.py that accepts a person's name and age as command-line arguments. The program should check that exactly two arguments are provided, convert the age to an integer, and print a message like 'Hello, Alice! You are 25 years old.' Make sure to follow the single logical line per physical line convention and do not use any semicolons.
Hints
- Remember to import sys at the top of your file.
- Use
len(sys.argv)to check that exactly 3 elements are present (script name plus two arguments). - Convert
sys.argv[2] to an integer usingint()since ages are numbers. - Use an f-string or string concatenation to format your output message.
- Each statement should be on its own line.
Summary
- 1Command-line arguments are values passed to a program when it is executed from the terminal. Python stores these arguments in the
sys.argvlist, wheresys.argv[0] is the script name andsys.argv[1],sys.argv[2], etc. are the actual arguments. - 2Always import sys at the top of your program before using
sys.argv. Check the length ofsys.argvbefore accessing specific indices to avoidIndexErrorexceptions. - 3Remember that all elements of
sys.argvare strings. Convert them to the appropriate type (int, float, etc.) before performing operations on them. - 4Follow the single logical line per physical line convention: write one complete Python statement per line and never use semicolons to combine multiple statements on a single line. This makes your code more readable and maintainable.
- 5When writing command-line programs, validate user input by checking argument counts and handling errors gracefully. This makes your programs robust and user-friendly.
At a glance
- Command-line arguments are passed to Python programs via the
sys.argvlist, wheresys.argv[0] is the script name and subsequent elements are the arguments provided by the user. - Always import sys, check the argument count before accessing specific indices, and convert string arguments to appropriate data types before using them in calculations.
- Python's design philosophy emphasizes one logical line per physical line of code; never use semicolons to combine multiple statements, as this violates readability conventions and is rarely seen in professional Python code.
- Validate command-line input by checking
len(sys.argv)and handling missing or invalid arguments gracefully to create robust, user-friendly programs. - Python's newline-based statement termination differs from languages like C and Java that require explicit semicolons, reflecting Python's focus on code clarity and readability.