1 min read 0 comments

The modules sys and argparse are just two modules I’ve learned recently. I’ve heard of the sys module before but have not paid close attention to it until now when I learned how to use sys.argv (link to documentation here). It is used when a creator of a Python app wants the app to be accessible in the command line. If an app uses some values for variables it needs to run, these values can be supplied at the command line at the same time the app or script is called. How this works is illustrated in the script below named, named argv_example.py:

import sys

print("The name of this script is {}".format(sys.argv[0]))
print("User supplied {} arguments at run time".format(len(sys.argv)))

for arg in sys.arg[1:]:
   print(arg)

Running this at the command line by typing python3 argv_example.py will give

The name of this script is argv_example.py
User supplied 1 arguments at run time

Typing python3 argv_example.py 1 2 3 4 will give:

The name of this script is argv_example.py
User supplied 5 arguments at run time
1
2
3
4

This can be taken advantage of in supplying additional arguments for when an application needs them when they are ran in the command line. For example, in creating the script for “FizzBuzz”, the sys.argv is used to have the option of supplying a number needed to run the program at the command line.

Running this script by supplying an additional argument, supposedly a number, will bypass the part where the script asks the user for a number.

The argparse module allows the construction of a more complex command line interface. The Python HOWTO tutorial is a nice resource in learning how to use it. Using this module, one can create an interface that supplies information on a Python application. Here is an example of such an interface. By supplying the argument “–help” after the name of the script, information on the app can be retrieved.

Furthermore, another information on available commands can also be retrieved:

I’m looking forward to using this in my future apps!