PYTHON STANDARD LIBRARY - Complete Guide For Python Programming (2015)

Complete Guide For Python Programming (2015)

PYTHON STANDARD LIBRARY

The Python Standard Library contains a huge number of useful modules and is part of every standard Python installation. we will explore some of the commonly used modules in this library. You can find complete details for all of the modules in the Python Standard Library in the 'Library Reference' section of the documentation that comes with your Python installation.

sys module

The sys module contains system-specific functionality. We have already seen that the sys.argv list contains the command-line arguments. For example, you want to check the version of the Python software being used; the sys module gives us that information.

$ python

>>> import sys

>>> sys.version_info

sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)

>>> sys.version_info.major == 2

True

logging module

What if you wanted to have some debugging messages or important messages to be stored somewhere so that you can check whether your program has been running as you would expect it? How do you "store somewhere" these messages? This can be achieved using the logging module.

Save as stdlib_logging.py:

import os, platform, logging

if platform.platform().startswith('Windows'):

logging_file = os.path.join(os.getenv('HOMEDRIVE'),

os.getenv('HOMEPATH'),

'test.log')

else:

logging_file = os.path.join(os.getenv('HOME'), 'test.log')

print "Logging to", logging_file

logging.basicConfig(

level=logging.DEBUG,

format='%(asctime)s : %(levelname)s : %(message)s',

filename = logging_file,

filemode = 'w',

)

logging.debug("Start of the program")

logging.info("Doing something")

logging.warning("Dying now")

Output:

$ python stdlib_logging.py

Logging to /Users/swa/test.log

$ cat /Users/swa/test.log

2014-03-29 09:27:36,660 : DEBUG : Start of the program

2014-03-29 09:27:36,660 : INFO : Doing something

2014-03-29 09:27:36,660 : WARNING : Dying now