Processing Command Line Arguments

When a Python script is run, its command-line arguments (if any) are stored in the list sys.argv.

Printing the Command Line Arguments

Code:


#!/usr/bin/env python
# file: echo.py

import sys
print sys.argv

Output:


> chmod +x echo.py
> echo.py tuna
['echo.py', 'tuna']
> echo.py tuna fish
['echo.py', 'tuna', 'fish']
> echo.py "tuna fish"
['echo.py', 'tuna fish']
> echo.py
['echo.py']
>

Computing the Hypotenuse of a Right Triangle

Code:


#!/usr/bin/env python
# file: hypotenuse.py

import sys, math

if len(sys.argv) != 3:  # the program name and the two arguments
  # stop the program and print an error message
  sys.exit("Must provide two positive numbers")

# Convert the two arguments from strings into numbers
x = float(sys.argv[1])
y = float(sys.argv[2])

print "Hypotenuse =", math.sqrt(x**2+y**2)

Output:


> hypotenuse.py 5 12
Hypotenuse = 13.0
> 

Python is Strongly Typed

You need to use the float to turn the command-line string into a floating point value. This is because Python is strongly typed. What does it mean to do:

  math.sqrt("16")
  math.sqrt("16a")
  math.sqrt("16a25")
  math.sqrt("sixteen")
  "1" + 2
?

This page based on Processing Command Line Arguments.


Andrew Dalke
Last modified: Tue Feb 3 12:34:22 SAST 2004