Functions · 6 / 27 Theory

main, command-line arguments and exit codes

The last two exercises of the lesson take the program away from the keyboard: they receive the data from the command line and return a code to the system.

The main function

A well-organized program has a main function with the main logic. It is usually protected with this condition:

def main():
    name = input()
    print(f"Hello {name}")

if __name__ == "__main__":
    main()

__name__ equals "__main__" only when the file is run directly, not when another program imports it. This way you can reuse your functions in other files without main() running.

Command-line arguments: sys.argv

When you run python calculator.py 3 + 4, the texts that come after the program name arrive in the sys.argv list:

import sys

print(sys.argv)   # ['calculator.py', '3', '+', '4']
  • sys.argv[0] is the name of the program.
  • sys.argv[1], sys.argv[2]… are the arguments, always as text: you must convert them with int() or float().
  • len(sys.argv) tells how many there are (counting the name).
import sys

def calculate(a, operation, b):
    if operation == "+":
        return a + b
    if operation == "-":
        return a - b
    if operation == "x":
        return a * b
    return a / b

print(calculate(int(sys.argv[1]), sys.argv[2], int(sys.argv[3])))

It is the structure of Calculator with command-line parameters. Notice that x is used for multiplication, because in many terminals * has a special meaning.

Exit codes

When a program ends, it returns a number to the operating system: 0 means everything went well and any other value indicates an error. This way other programs or scripts know whether it worked. In Python it is done with sys.exit():

import sys

if len(sys.argv) != 4:
    sys.exit(1)       # wrong number of arguments

try:
    a = int(sys.argv[1])
except ValueError:
    sys.exit(3)       # an argument is not a number

sys.exit(0)           # all correct

Return value from Main asks exactly for this: a different code for each kind of failure. Use try/except ValueError to detect the arguments that are not numbers (you saw it in article 4) and sys.exit(code) in each case.

One detail: after sys.exit() the program ends immediately; no later return or else is needed.