Skip to content

Interacting with the User

Command line options

argv

By importing the package argv, we get access to the list of arguments given on the command-line, sys.argv.

This is a list that contains all of the whitespace-delimited chunks of text given with the running command. The first item (item number 0) is always the name of the program itself.

In the example below, we use sys.argv to take in a name for the person to say "hello" to.

hellosomeone.py from the beginning to the end
#!/usr/bin/env python
import sys

name=sys.argv[1]

print(f"Hello {name}!")

An example of this running:

Using sys.argv

If no data is given, then sys.argv[1] doesn't exist, so we should check for this first. The improved example below demonstrates how this can be done:

hellosomeone2.py from the beginning to the end
#!/usr/bin/env python
import sys


if len(sys.argv) > 1:
    name=sys.argv[1]
    print(f"Hello {name}!")
else:
    print("You must supply a name!")

An example of this running with and without a supplied name:

Using sys.argv

Check Your Understanding

Can you write a version of the code above so that there is a message displayed also if there are too many words given? For example ./hellosomeone3.py James the cat should result in a message saying only one name must be given.

It is also possible to list all of the arguments. Here is one way to do that:

listem.py from the beginning to the end
#!/usr/bin/env python
import sys

print("Showing all arguments")



for i in range(len(sys.argv)):
    print(f"Argument {i:>3}: {sys.argv[i]}")

An example of this running:

Listing arguments with argv

getopt

Rather than have to decipher command-line arguments ourselves, it is useful to use a library that can simplify the process and, at the same time, provide the same kind of features we expect from other commands, like switches -- ls -a or ls --color, for example, are examples of passing optional information to the ls command.

The getopt library implements these features and is widely used: https://docs.python.org/3.8/library/getopt.html

User input

Coming soon

Sanitisation

Coming soonish

More?

Coming whenever