16-standard-library.pd 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. # Standard Library
  2. The Python Standard Library contains a huge number of useful modules and is part of every standard Python installation. It is important to become familiar with the Python Standard Library since many problems can be solved quickly if you are familiar with the range of things that these libraries can do.
  3. 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](http://docs.python.org/py3k/library/index.html) of the documentation that comes with your Python installation.
  4. Let us explore a few useful modules.
  5. Note
  6. : If you find the topics in this chapter too advanced, you may skip this chapter. However, I highly recommend coming back to this chapter when you are more comfortable with programming using Python.
  7. ## sys module
  8. The `sys` module contains system-specific functionality. We have already seen that the `sys.argv` list contains the command-line arguments.
  9. 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.
  10. ~~~
  11. $ python3
  12. >>> import sys
  13. >>> sys.version_info
  14. sys.version_info(major=3, minor=3, micro=0, releaselevel='final', serial=0)
  15. >>> sys.version_info.major >= 3
  16. True
  17. ~~~
  18. How It Works:
  19. 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:
  20. Save as `versioncheck.py`:
  21. ~~~python
  22. import sys, warnings
  23. if sys.version_info.major < 3:
  24. warnings.warn("Need Python 3.0 for this program to run",
  25. RuntimeWarning)
  26. else:
  27. print('Proceed as normal')
  28. ~~~
  29. Output:
  30. ~~~
  31. $ python2.7 versioncheck.py
  32. versioncheck.py:6: RuntimeWarning: Need Python 3.0 for this program to run
  33. RuntimeWarning)
  34. $ python3 versioncheck.py
  35. Proceed as normal
  36. ~~~
  37. How It Works:
  38. 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.
  39. ## logging module
  40. 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.
  41. Save as `use_logging.py`:
  42. ~~~python
  43. import os, platform, logging
  44. if platform.platform().startswith('Windows'):
  45. logging_file = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'), 'test.log')
  46. else:
  47. logging_file = os.path.join(os.getenv('HOME'), 'test.log')
  48. print("Logging to", logging_file)
  49. logging.basicConfig(
  50. level=logging.DEBUG,
  51. format='%(asctime)s : %(levelname)s : %(message)s',
  52. filename = logging_file,
  53. filemode = 'w',
  54. )
  55. logging.debug("Start of the program")
  56. logging.info("Doing something")
  57. logging.warning("Dying now")
  58. ~~~
  59. Output:
  60. ~~~
  61. $ python3 use_logging.py
  62. Logging to C:\Users\swaroop\test.log
  63. ~~~
  64. If we check the contents of `test.log`, it will look something like this:
  65. ~~~
  66. 2012-10-26 16:52:41,339 : DEBUG : Start of the program
  67. 2012-10-26 16:52:41,339 : INFO : Doing something
  68. 2012-10-26 16:52:41,339 : WARNING : Dying now
  69. ~~~
  70. How It Works:
  71. We use three modules from the standard library - the `os` module for interacting with the operating system, the `platform` module for information about the platform i.e. the operating system and the `logging` module to *log* information.
  72. First, we check which operating system we are using by checking the string returned by `platform.platform()` (for more information, see `import platform; help(platform)`). If it is Windows, we figure out the home drive, the home folder and the filename where we want to store the information. Putting these three parts together, we get the full location of the file. For other platforms, we need to know just the home folder of the user and we get the full location of the file.
  73. We use the `os.path.join()` function to put these three parts of the location together. The reason to use a special function rather than just adding the strings together is because this function will ensure the full location matches the format expected by the operating system.
  74. We configure the `logging` module to write all the messages in a particular format to the file we have specified.
  75. Finally, we can put messages that are either meant for debugging, information, warning or even critical messages. Once the program has run, we can check this file and we will know what happened in the program, even though no information was displayed to the user running the program.
  76. ## Module of the Week Series
  77. There is much more to be explored in the standard library such as [debugging](http://docs.python.org/py3k/library/pdb.html), [handling command line options](http://docs.python.org/py3k/library/argparse.html), [regular expressions](http://docs.python.org/py3k/library/re.html) and so on.
  78. The best way to further explore the standard library is to read Doug Hellmann's excellent [Python Module of the Week](http://www.doughellmann.com/projects/PyMOTW/) series or reading the [Python documentation](http://docs.python.org/py3k/).
  79. ## Summary
  80. We have explored some of the functionality of many modules in the Python Standard Library. It is highly recommended to browse through the [Python Standard Library documentation](http://docs.python.org/py3k/library/index.html) to get an idea of all the modules that are available.
  81. Next, we will cover various aspects of Python that will make our tour of Python more *complete*.