Chapter 5 Command line arguments

5.1 Learning objectives

  • Understand how to accept command line arguments in Python scripts

  • Learn how to access command line arguments using the sys module

  • Understand how to handle command line arguments

5.2 Printing All Command Line Arguments

Let’s make our Python scripts interactive by accepting input from the command line. Create a new file called 02-arguments.py and type:

```python
#!/usr/bin/env python3

import sys

print(sys.argv)
```
  • Save the file and make it executable:

    chmod +x 02-arguments.py
  • Now run it directly with some arguments:

    ./02-arguments.py hello world 123

    You’ll see output like ['./02-arguments.py', 'hello', 'world', '123']

The sys module provide access to the system-specific parameter. The variable sys.argv contains all command line arguments passed to your script, including the script name itself as the first element.

5.3 Understanding Lists

Lists in Python are ordered collections of items enclosed in square brackets, like [1, 2, 3] or ["apple", "banana"]. Lists can contain different types of data and are accessed by the position (index), starting from 0. For example, my_list[0] gets the first item, my_list[1] gets the second item, and so in.

5.4 Accessing Specific Arguments

  • Lets modify our script to print just the second command line argument:

    #!/usr/bin/env python3
    
    import sys
    
    print("Script name:", sys.argv[0])
    print("First argument:", sys.argv[1])
  • Run it with: ./02-arguments.py hello

    This prints:

    Script name: ./02-arguments.py
    First argument: hello

    Notice how sys.argv[0] is always the script name, so the first actual argument is at index 1

    Warning: If you don’t provide enough arguments, Python will crash with an “IndexError”. We’ll learn to handle this with if statements later

5.5 Arguments Are Strings

Command line arguments are always strings, even if they look like numbers.

  • Update 02-arguments.py

    #!/usr/bin/env python3
    
    import sys
    
    # This won't work as expected
    result = sys.argv[1] + sys.argv[2]
    print("Without conversion:", result)
    
    # Convert strings to integers first
    num1 = int(sys.argv[1])
    num2 = int(sys.argv[2])
    print("With conversion:", num1 + num2)
  • Run it with: ./02-arguments.py 5 3

    Output:

    Without conversion: 53
    With conversion: 8

Without conversion, Python concatenates the strings “5” and “3” into “53”. The int() function converts string representations of numbers into actual integers that can be used in mathematical operations.

5.6 Summary

Congratulations! You have just:

  • Created a Python script that accepts command line arguments

  • Accessed specific arguments using sys.argv