Commandline Arguments (sys.argv)

Operating Systems and Programs

  • The Shell is just one way to start a program

    • Generally speaking, programs are started by other programs (the shell is just an ordinary program, after all)

    • ⟶ service manager, Cron-Jobs

  • Deal between OS and program

    • Argument vector (⟶ argv)

    • Environment variables

    • Exit status

$ ls -l

Argument vector: ['ls', '-l']

Commandline Arguments in Python

import sys

print('sys.argv:', sys.argv)
print('sys.argv[0] (program name):', sys.argv[0])
print('sys.argv[1] (firstname):', sys.argv[1])
print('sys.argv[2] (lastname):', sys.argv[2])
$ python args.py Joerg Faschingbauer
sys.argv: ['args.py', 'Joerg', 'Faschingbauer']
sys.argv[0] (program name): args.py
sys.argv[1] (firstname): Joerg
sys.argv[2] (lastname): Faschingbauer

Argument vector: ['args.py', 'Joerg', 'Faschingbauer']

Cosmetics: Rudimentary Argument Parsing

import sys

# rudimentarily parsing the commandline: check for number of arguments
if len(sys.argv) != 3:
    print('Expecting two parameters:', sys.argv[0], '<firstname> <lastname>', 
          file=sys.stderr)   # stderr is where errors belong!
    
    # exit status != 0 for "terminated with an error"
    sys.exit(1)

print('sys.argv:', sys.argv)
print('sys.argv[0] (program name):', sys.argv[0])
print('sys.argv[1] (firstname):', sys.argv[1])
print('sys.argv[2] (lastname):', sys.argv[2])

# implicitly terminated with exit status 0 for "all fine"
$ python args-parsing.py Joerg
Expecting two parameters: args-parsing.py <firstname> <lastname>