Python3 Command Line Arguments
# Python3 Command Line Arguments
When developing command-line interfaces (CLIs) or automating tasks with Python, you often need to pass parameters to your scripts at runtime. Python provides several built-in ways to handle command-line arguments, ranging from simple list-based access to advanced parsing modules.
This tutorial covers how to read and parse command-line arguments in Python 3 using the built-in `sys` and `getopt` modules.
---
## 1. Basic Argument Parsing with `sys.argv`
The simplest way to access command-line arguments in Python is by using the `sys` module's `sys.argv` list.
* **`sys.argv`**: A list containing the command-line arguments passed to the Python script.
* **`len(sys.argv)`**: Returns the total number of command-line arguments (including the script name itself).
* **`sys.argv`**: Always represents the name of the script being executed.
### Example: Using `sys.argv`
Create a file named `test.py` with the following code:
```python
#!/usr/bin/python3
import sys
# Print the total number of arguments
print('Number of arguments:', len(sys.argv), 'arguments.')
# Print the list of all arguments
print('Argument list:', str(sys.argv))
# Print the script name
print('Script name:', str(sys.argv))
```
### Execution and Output
Run the script in your terminal with three sample arguments:
```bash
$ python3 test.py arg1 arg2 arg3
```
**Output:**
```text
Number of arguments: 4 arguments.
Argument list: ['test.py', 'arg1', 'arg2', 'arg3']
Script name: test.py
```
---
## 2. Advanced Parsing with the `getopt` Module
While `sys.argv` is useful for simple inputs, it becomes difficult to manage when your script requires options (flags) like `-h`, `-v`, or parameters with values like `-o output.txt`.
The `getopt` module helps parse command-line options and arguments. It supports both short options (e.g., `-n`) and long options (e.g., `--name`).
### The `getopt.getopt` Method
The `getopt.getopt` method parses command-line options and parameter lists.
#### Syntax
```python
getopt.getopt(args, options[, long_options])
```
#### Parameter Descriptions
* **`args`**: The list of arguments to be parsed. Typically, this is `sys.argv[1:]` (excluding the script name).
* **`options`**: A string defining the short options. A colon (`:`) after a letter indicates that the option requires an accompanying argument (e.g., `"n:"` means `-n` must be followed by a value).
* **`long_options`**: A list of strings defining the long options. An equal sign (`=`) after an option name indicates that the option requires an accompanying argument (e.g., `"name="` means `--name` must be followed by a value).
#### Return Value
This method returns a tuple containing two elements:
1. A list of `(option, value)` pairs.
2. A list of remaining positional arguments (arguments left over after all option flags have been stripped).
---
### Example 1: Parsing Short Options (`-`)
In this example, we define a `site()` function that accepts a site name (`-n`) and a URL (`-u`).
```python
import sys
import getopt
def site():
name = None
url = None
# Exclude the script name from the argument list
argv = sys.argv[1:]
try:
# "n:u:" means -n and -u options both require an argument
opts, args = getopt.getopt(argv, "n:u:")
except getopt.GetoptError:
print("Error parsing arguments")
sys.exit(2)
for opt, arg in opts:
if opt == '-n':
name = arg
elif opt == '-u':
url = arg
print(f"Site Name: {name} | URL: {url}")
if __name__ == "__main__":
site()
```
#### Execution and Output
```bash
$ python3 test.py -n YouTip -u www.youtip.co
```
**Output:**
```text
Site Name: YouTip | URL: www.youtip.co
```
---
### Example 2: Parsing Long Options (`--`)
You can extend your script to support both short options (`-n`, `-u`) and long options (`--name`, `--url`).
```python
import sys
import getopt
def site():
name = None
url = None
argv = sys.argv[1:]
try:
# Define short options "n:u:" and corresponding long options ["name=", "url="]
opts, args = getopt.getopt(argv, "n:u:", ["name=", "url="])
except getopt.GetoptError:
print("Error parsing arguments")
sys.exit(2)
for opt, arg in opts:
if opt in ('-n', '--name'):
name = arg
elif opt in ('-u', '--url'):
url = arg
print(f"Site Name: {name} | URL: {url}")
if __name__ == "__main__":
site()
```
#### Execution and Output
You can now use either short or long options interchangeably:
```bash
$ python3 test.py --name YouTip --url www.youtip.co
```
**Output:**
```text
Site Name: YouTip | URL: www.youtip.co
```
---
## 3. Exception Handling: `getopt.GetoptError`
The `getopt.GetoptError` exception is raised when an unrecognized option is passed, or when an option that requires an argument is provided without one.
### Comprehensive Example: File Input/Output Script
Below is a complete script demonstrating how to handle help flags (`-h`), input files (`-i`), output files (`-o`), and how to gracefully handle parsing errors.
```python
#!/usr/bin/python3
import sys
import getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
# 'h' does not require an argument; 'i:' and 'o:' do.
opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
except getopt.GetoptError:
# Print usage instructions and exit if parsing fails
print('Usage: test.py -i -o ')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('Usage: test.py -i -o ')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print('Input file is:', inputfile)
print('Output file is:', outputfile)
if __name__ == "__main__":
main(sys.argv[1:])
```
### Execution and Output
#### 1. Requesting Help:
```bash
$ python3 test.py -h
```
**Output:**
```text
Usage: test.py -i -o
```
#### 2. Passing Valid Arguments:
```bash
$ python3 test.py -i source.txt -o destination.txt
```
**Output:**
```text
Input file is: source.txt
Output file is: destination.txt
```
#### 3. Triggering an Error (Missing Argument for `-i`):
```bash
$ python3 test.py -i
```
**Output:**
```text
Usage: test.py -i -o
```
---
## Summary and Considerations
* **`sys.argv`** is best for quick scripts with simple, positional arguments.
* **`getopt`** mimics the classic C-style `getopt()` function. It is excellent for standard command-line flags but requires manual loop handling to assign variables.
* **Alternative (Modern Python)**: For complex CLI applications, Python also provides the built-in **`argparse`** module, which automatically generates help messages and handles type validation. However, `getopt` remains a lightweight, highly compatible choice for standard Unix-like option parsing.
YouTip