Skip to content
This repository was archived by the owner on Feb 27, 2026. It is now read-only.

Commit b090af8

Browse files
[Edit] Python: Python CLI arguments (#7639)
* [Edit] Python: Python CLI arguments * Update command-line-arguments.md * [Edit] Python: Python CLI arguments * Update content/python/concepts/command-line-arguments/command-line-arguments.md ---------
1 parent 24397c0 commit b090af8

1 file changed

Lines changed: 132 additions & 56 deletions

File tree

Lines changed: 132 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,106 +1,182 @@
11
---
22
Title: 'Command Line Arguments'
3-
Description: 'Python offers several methods of parsing command line arguments that are used when launching a program.'
3+
Description: 'Provides methods to accept input values when running Python scripts from the terminal'
44
Subjects:
5+
- 'Code Foundations'
56
- 'Computer Science'
6-
- 'Data Science'
77
Tags:
8-
- 'Input'
98
- 'Arguments'
10-
- 'Bash/Shell'
119
- 'Command Line'
10+
- 'Input'
11+
- 'Modules'
1212
CatalogContent:
1313
- 'learn-python-3'
1414
- 'paths/computer-science'
1515
---
1616

17-
Python offers several methods of parsing **command line arguments** that are used when launching a program. The user has the option of passing various parameters to the program by adding them after the program name. These parameters can be accessed through various modules. The parameter names are left up to the programmer. By convention the parameter `-h` or `--help` (and `/h` and `/help` in Windows) is reserved to print a help message to the console listing the various command line options recognized by the program.
18-
19-
Arguments are passed differently depending on the operating system:
17+
**Command line arguments** are values passed to a Python program when running it from the terminal or command prompt. They allow users to provide input data to a program without modifying the source code, making programs more flexible and reusable by accepting different parameters at runtime.
2018

21-
- Unix-like arguments are a single letter preceded by a dash (`-h`) or a word preceded by two dashes (`--help`).
22-
- Windows arguments are a letter or a whole word preceded by a slash (`/h` or `/help`).
19+
## Ways to Handle Command Line Arguments
2320

24-
## Parsing With `sys.argv`
21+
Python provides several built-in modules to handle command line arguments, each with different levels of complexity and functionality.
2522

26-
The `sys` module offers the most straightforward method of accessing command line arguments, but it also requires the programmer to do most of the work interpreting them. With the `sys` module, the arguments are passed along in a simple list structure named `sys.argv`.
23+
### Using `sys.argv`
2724

28-
The first item in the list, `sys.argv[0]` is the name used to launch the Python program, along with the path used. Each subsequent item is a space-delimited argument from the command line used to launch the program. If an argument requires embedded spaces, it needs to be enclosed in quotes to be parsed correctly.
25+
The `sys.argv` module provides the simplest way to access command line arguments. It stores all arguments passed to the script as a list of strings, where `sys.argv[0]` contains the script name itself.
2926

30-
### Example
27+
#### Example: Basic `sys.argv` Usage
3128

32-
This prints the script name followed by a list of the command line arguments passed on to the program.
29+
This example demonstrates how to access and use Python command line arguments using the `sys` module:
3330

3431
```py
3532
import sys
3633

37-
print(f"The program name used to launch me is {sys.argv[0]}.")
38-
print("I was passed the following arguments:")
39-
for arg in sys.argv[1:]:
40-
print(arg)
34+
# Display all command line arguments
35+
print("Script name:", sys.argv[0])
36+
print("All arguments:", sys.argv)
37+
38+
# Check if arguments are provided
39+
if len(sys.argv) > 1:
40+
name = sys.argv[1]
41+
print(f"Hello, {name}!")
42+
else:
43+
print("No name provided. Usage: python script.py <name>")
4144
```
4245

43-
If this is named `test.py` it can be launched with the following result:
46+
When running this script with `python greet.py Alice`, it produces the following output:
4447

45-
```bash
46-
$ test.py --arg1 --arg2 "arg 3"
47-
The program name used to launch me is test.py.
48-
I was passed the following arguments:
49-
--arg1
50-
--arg2
51-
arg 3
48+
```shell
49+
Script name: greet.py
50+
All arguments: ['greet.py', 'Alice']
51+
Hello, Alice!
5252
```
5353

54-
## Parsing With `getopt()`
54+
The `sys.argv` list contains the script name as the first element, followed by all arguments passed from the command line. All arguments are stored as strings, so type conversion is needed for numeric operations.
55+
56+
### Using `getopt`
57+
58+
The `getopt` module provides a more structured approach to parsing command line options, similar to the C `getopt()` function. It supports both short options (single letters with a hyphen) and long options (words with double hyphens).
5559

56-
Using `getopt()` requires importing both the `sys` and `getopt` modules to work. With `getopt`, parameter validation is possible. This is done by passing a list of the command line arguments themselves, a string of short (one character) options, and a list of long (full word) options. To indicate that the option requires a value to be passed along with it, the short option is followed by a colon (`:`), and the long option is followed by an equals sign (`=`).
60+
#### Example: File Processing with `getopt`
5761

58-
To set up options for "help", "argument", and a "value" that requires an additional passed value, would look like this:
62+
This example shows how to create a script that processes input and output files with optional help:
5963

60-
- The short options would be a string like `"hav:"`.
61-
- The long options would be a list like `["help","argument","value="]`.
64+
```py
65+
import sys
66+
import getopt
67+
68+
def main():
69+
input_file = ""
70+
output_file = ""
71+
72+
try:
73+
# Parse command line options
74+
opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help", "input=", "output="])
75+
except getopt.GetoptError as err:
76+
print(f"Error: {err}")
77+
print("Usage: python script.py -i <inputfile> -o <outputfile>")
78+
sys.exit(2)
79+
80+
for opt, arg in opts:
81+
if opt in ("-h", "--help"):
82+
print("Usage: python script.py -i <inputfile> -o <outputfile>")
83+
print("Options:")
84+
print(" -i, --input Input file path")
85+
print(" -o, --output Output file path")
86+
print(" -h, --help Show this help message")
87+
sys.exit()
88+
elif opt in ("-i", "--input"):
89+
input_file = arg
90+
elif opt in ("-o", "--output"):
91+
output_file = arg
92+
93+
# Process the files
94+
if input_file and output_file:
95+
print(f"Processing: {input_file} -> {output_file}")
96+
else:
97+
print("Both input and output files are required")
98+
sys.exit(1)
99+
100+
if __name__ == "__main__":
101+
main()
102+
```
62103

63-
### Syntax
104+
Running this script with `python process.py -i data.txt -o result.txt` produces:
64105

65-
```python
66-
options, values = getopt.getopt(arguments, short_options, long_options)
106+
```shell
107+
Processing: data.txt -> result.txt
67108
```
68109

69-
Where the results of `getopt()` are `options` which is a list of option/value pairs, and `values` which is a list of arguments left after the option list was stripped. The parameters passed to `getopt()` are `arguments`, a list of the arguments as provided by `sys.argv` without the initial program name, the string `short_options` and the list `long_options` as described above.
110+
The `getopt.getopt()` function parses the argument list and returns a tuple containing option-value pairs and remaining arguments. Short options require a colon after the letter if they expect a value.
70111

71-
If `arguments` contains an option that is not in `short_options` or `long_options` then an `getopt.error` exception is thrown.
112+
### Using `argparse`
72113

73-
### Example
114+
The `argparse` module is the most powerful and user-friendly way to handle command line arguments. It automatically generates help messages, handles errors gracefully, and supports various argument types including positional and optional arguments.
74115

75-
This prints the option/value pairs passed as command line arguments.
116+
#### Example: User Greeting with `argparse`
117+
118+
This example demonstrates creating a user-friendly command line interface:
76119

77120
```py
78-
import sys, getopt
121+
import argparse
122+
123+
# Create argument parser
124+
parser = argparse.ArgumentParser(description="Greet users with customizable messages")
125+
126+
# Add positional argument
127+
parser.add_argument("name", help="Name of the person to greet")
79128

80-
arguments = sys.argv[1:]
81-
short_options = "hav:"
82-
long_options = ["help","argument","value="]
129+
# Add optional arguments
130+
parser.add_argument("-g", "--greeting", default="Hello",
131+
help="Greeting message (default: Hello)")
132+
parser.add_argument("-u", "--uppercase", action="store_true",
133+
help="Convert output to uppercase")
83134

84-
options, values = getopt.getopt(arguments, short_options, long_options)
135+
# Parse arguments
136+
args = parser.parse_args()
85137

86-
for o, v in options:
87-
print(f"Option is {o}. Value is {v}.")
138+
# Create greeting message
139+
message = f"{args.greeting}, {args.name}!"
140+
141+
# Apply uppercase if requested
142+
if args.uppercase:
143+
message = message.upper()
144+
145+
print(message)
88146
```
89147

90-
If this is named **test.py** it can be launched with the following results:
148+
When executed with `python greet.py Alice -g "Good morning" --uppercase`, the output is:
91149

92-
```bash
93-
$ test.py -a --value=test
94-
Option is -a. Value is .
95-
Option is --value. Value is test.
150+
```shell
151+
GOOD MORNING, ALICE!
96152
```
97153

98-
**Note**: Since `-a` wasn't defined as requiring a value passed to it, the corresponding value for the option is empty.
154+
The `argparse` module automatically provides help documentation when using `-h` or `--help`, validates required arguments, and converts values to appropriate types. It handles argument parsing errors by displaying helpful error messages and usage information.
155+
156+
## Frequently Asked Questions
157+
158+
### 1. What are command-line arguments in Python?
159+
160+
Command line arguments in Python are values passed to a script when executing it from the terminal. They provide a way to customize program behavior without modifying the source code, making scripts more flexible and reusable.
161+
162+
### 2. What are the 5 arguments in Python?
163+
164+
There isn't a fixed set of "5 arguments" in Python. The number and type of command line arguments depend on what the program is designed to accept. However, common argument types include: positional arguments (required values), optional arguments (flags with values), boolean flags (on/off switches), help arguments, and version arguments.
165+
166+
### 3. How to pass an argument to a Python script from the command-line?
167+
168+
To pass arguments to a Python script, include them after the script name when running it:
169+
170+
- `python script.py argument1 argument2` - passes multiple arguments
171+
- `python script.py --option value` - passes an option with a value
172+
- `python script.py -f --verbose` - passes flags and options
173+
174+
### 4. What is an example of a command-line argument?
99175

100-
## Other Methods of Parsing the Command Line
176+
A simple example is running `python calculator.py 10 5 add`, where:
101177

102-
There are other methods of parsing command line arguments in Python, which add varying functionality to the task. Some examples include:
178+
- `calculator.py` is the script name
179+
- `10` and `5` are numeric arguments
180+
- `add` is an operation argument
103181

104-
- The `argparse` module, that's been available since Python 3.2, validates fixed and optional arguments and offers a default help message displaying the accepted arguments.
105-
- The `docopt` module, which is complex and versatile, provides its own language to describe command line options.
106-
- The `click` module provides arbitrary nesting of commands and automatic help page generation.
182+
The script can access these values using `sys.argv`, `getopt`, or `argparse` to perform the specified calculation.

0 commit comments

Comments
 (0)