Learning Resources
 

sys module


The sys module contains system-specific functionality. We have already seen that the sys.argv list contains the command-line arguments.

Suppose we want to check the version of the Python command being used so that, say, we want to ensure that we are using at least version 3. The sys module gives us such functionality.

>>> import sys
>>> sys.version_info
(3, 0, 0, 'beta', 2)
>>> sys.version_info[0] >= 3
True

How It Works:

The sys module has a version_info tuple that gives us the version information. The first entry is the major version. We can check this to, for example, ensure the program runs only under Python 3.0:

#!/usr/bin/python
# Filename: versioncheck.py
import sys, warnings
if sys.version_info[0] < 3:
    warnings.warn("Need Python 3.0 for this program to run",
        RuntimeWarning)
else:
    print('Proceed as normal')

Output:

   $ python2.5 versioncheck.py
   versioncheck.py:6: RuntimeWarning: Need Python 3.0 for this program to run
     RuntimeWarning)
   
   $ python3 versioncheck.py
   Proceed as normal

How It Works:

We use another module from the standard library called warnings that is used to display warnings to the end-user. If the Python version number is not at least 3, we display a corresponding warning.

 

-Swaroopch