Command-line programs · 1 / 15 Theory

Command-line programs and sys.argv

So far your programs asked for data with input(). But many real tools (git, pip, python itself) are used from the terminal, typing the program name followed by arguments: python greet.py Ana 3. These tools are called command-line programs (CLI, *command-line interface*) and can be combined with each other and automated.

Arguments arrive in sys.argv

Python stores what you type after the script name in the sys.argv list. Element 0 is the program name and from 1 on are the arguments, always as text.

What you type in the terminalValue of sys.argv
python greet.py['greet.py']
python greet.py Ana['greet.py', 'Ana']
python greet.py Ana 3['greet.py', 'Ana', '3']
python greet.py "Ana Maria"['greet.py', 'Ana Maria'] (quotes group words)

So that the examples in this article run on their own, we assign sys.argv by hand, simulating what there would be after typing the command. In a real program you would not write that line.

import sys

sys.argv = ["greet.py", "Ana", "3"]   # as if you typed: python greet.py Ana 3

print(sys.argv)         # ['greet.py', 'Ana', '3']
print(sys.argv[1:])     # ['Ana', '3']
print(len(sys.argv))    # 3

Everything is text: you must convert

Even if you type a number, sys.argv contains text. Convert with int() or float(), and remember it can raise ValueError.

import sys

sys.argv = ["add.py", "4", "8", "x"]

numbers = []
for text in sys.argv[1:]:
    try:
        numbers.append(int(text))
    except ValueError:
        print(f"Invalid argument: {text}")   # Invalid argument: x
print(sum(numbers))                           # 12

It is the basis of Sum of the arguments.

Missing or optional arguments

If the user does not type an argument, sys.argv[2] raises IndexError. Check the length first and give a default value.

import sys

sys.argv = ["greet.py", "Ana"]

if len(sys.argv) < 2:
    print("Usage: greet.py name [times]")
else:
    name = sys.argv[1]
    times = int(sys.argv[2]) if len(sys.argv) > 2 else 1
    for _ in range(times):
        print(f"Hello, {name}")   # Hello, Ana

You practise it in Greeting with arguments.

Exit code

Every program finishes with an exit code: 0 means it went well and any other number indicates an error. With sys.exit(code) you set it yourself; other programs (or scripts) check it to decide what to do. You will see it in detail in article 4.

import sys

try:
    sys.exit(1)        # ends the program with code 1
except SystemExit as e:
    print(e.code)      # 1   (sys.exit raises the SystemExit exception)

Standard input, output and error

Every program has three channels: standard input sys.stdin (where input() reads from), standard output sys.stdout (where print() writes) and standard error sys.stderr, for error messages. That way, normal output can be sent to a file or to another program without mixing it with errors.

import io
import sys

sys.stdin = io.StringIO("hello world\nanother line\n")   # we simulate the input

text = sys.stdin.read()           # reads ALL the input
print(len(text.splitlines()))     # 2
print(len(text.split()))          # 4

sys.stdin = sys.__stdin__         # we restore the real input

To write an error: print("message", file=sys.stderr). In the terminal you can chain programs with a pipe (|): cat text.txt | python counter.py sends the file to your program's input. With Counter like wc you will practise exactly that.

if __name__ == "__main__"

A Python file can be run directly (python greet.py) or imported from another one. The __name__ variable is "__main__" only in the first case, so it is used to make the program start only when run, without bothering when imported.

def greet(name):
    return f"Hello, {name}"

if __name__ == "__main__":
    print(greet("Ana"))   # Hello, Ana   (only if run directly)