You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

351 lines
11 KiB

7 years ago
  1. .. _tut-brieftour:
  2. **********************************
  3. Brief Tour of the Standard Library
  4. **********************************
  5. .. _tut-os-interface:
  6. Operating System Interface
  7. ==========================
  8. The :mod:`os` module provides dozens of functions for interacting with the
  9. operating system::
  10. >>> import os
  11. >>> os.getcwd() # Return the current working directory
  12. 'C:\\Python39'
  13. >>> os.chdir('/server/accesslogs') # Change current working directory
  14. >>> os.system('mkdir today') # Run the command mkdir in the system shell
  15. 0
  16. Be sure to use the ``import os`` style instead of ``from os import *``. This
  17. will keep :func:`os.open` from shadowing the built-in :func:`open` function which
  18. operates much differently.
  19. .. index:: builtin: help
  20. The built-in :func:`dir` and :func:`help` functions are useful as interactive
  21. aids for working with large modules like :mod:`os`::
  22. >>> import os
  23. >>> dir(os)
  24. <returns a list of all module functions>
  25. >>> help(os)
  26. <returns an extensive manual page created from the module's docstrings>
  27. For daily file and directory management tasks, the :mod:`shutil` module provides
  28. a higher level interface that is easier to use::
  29. >>> import shutil
  30. >>> shutil.copyfile('data.db', 'archive.db')
  31. 'archive.db'
  32. >>> shutil.move('/build/executables', 'installdir')
  33. 'installdir'
  34. .. _tut-file-wildcards:
  35. File Wildcards
  36. ==============
  37. The :mod:`glob` module provides a function for making file lists from directory
  38. wildcard searches::
  39. >>> import glob
  40. >>> glob.glob('*.py')
  41. ['primes.py', 'random.py', 'quote.py']
  42. .. _tut-command-line-arguments:
  43. Command Line Arguments
  44. ======================
  45. Common utility scripts often need to process command line arguments. These
  46. arguments are stored in the :mod:`sys` module's *argv* attribute as a list. For
  47. instance the following output results from running ``python demo.py one two
  48. three`` at the command line::
  49. >>> import sys
  50. >>> print(sys.argv)
  51. ['demo.py', 'one', 'two', 'three']
  52. The :mod:`argparse` module provides a mechanism to process command line arguments.
  53. It should always be preferred over directly processing ``sys.argv`` manually.
  54. Take, for example, the below snippet of code::
  55. >>> import argparse
  56. >>> from getpass import getuser
  57. >>> parser = argparse.ArgumentParser(description='An argparse example.')
  58. >>> parser.add_argument('name', nargs='?', default=getuser(), help='The name of someone to greet.')
  59. >>> parser.add_argument('--verbose', '-v', action='count')
  60. >>> args = parser.parse_args()
  61. >>> greeting = ["Hi", "Hello", "Greetings! its very nice to meet you"][args.verbose % 3]
  62. >>> print(f'{greeting}, {args.name}')
  63. >>> if not args.verbose:
  64. >>> print('Try running this again with multiple "-v" flags!')
  65. .. _tut-stderr:
  66. Error Output Redirection and Program Termination
  67. ================================================
  68. The :mod:`sys` module also has attributes for *stdin*, *stdout*, and *stderr*.
  69. The latter is useful for emitting warnings and error messages to make them
  70. visible even when *stdout* has been redirected::
  71. >>> sys.stderr.write('Warning, log file not found starting a new one\n')
  72. Warning, log file not found starting a new one
  73. The most direct way to terminate a script is to use ``sys.exit()``.
  74. .. _tut-string-pattern-matching:
  75. String Pattern Matching
  76. =======================
  77. The :mod:`re` module provides regular expression tools for advanced string
  78. processing. For complex matching and manipulation, regular expressions offer
  79. succinct, optimized solutions::
  80. >>> import re
  81. >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
  82. ['foot', 'fell', 'fastest']
  83. >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
  84. 'cat in the hat'
  85. When only simple capabilities are needed, string methods are preferred because
  86. they are easier to read and debug::
  87. >>> 'tea for too'.replace('too', 'two')
  88. 'tea for two'
  89. .. _tut-mathematics:
  90. Mathematics
  91. ===========
  92. The :mod:`math` module gives access to the underlying C library functions for
  93. floating point math::
  94. >>> import math
  95. >>> math.cos(math.pi / 4)
  96. 0.70710678118654757
  97. >>> math.log(1024, 2)
  98. 10.0
  99. The :mod:`random` module provides tools for making random selections::
  100. >>> import random
  101. >>> random.choice(['apple', 'pear', 'banana'])
  102. 'apple'
  103. >>> random.sample(range(100), 10) # sampling without replacement
  104. [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
  105. >>> random.random() # random float
  106. 0.17970987693706186
  107. >>> random.randrange(6) # random integer chosen from range(6)
  108. 4
  109. The :mod:`statistics` module calculates basic statistical properties
  110. (the mean, median, variance, etc.) of numeric data::
  111. >>> import statistics
  112. >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
  113. >>> statistics.mean(data)
  114. 1.6071428571428572
  115. >>> statistics.median(data)
  116. 1.25
  117. >>> statistics.variance(data)
  118. 1.3720238095238095
  119. The SciPy project <https://scipy.org> has many other modules for numerical
  120. computations.
  121. .. _tut-internet-access:
  122. Internet Access
  123. ===============
  124. There are a number of modules for accessing the internet and processing internet
  125. protocols. Two of the simplest are :mod:`urllib.request` for retrieving data
  126. from URLs and :mod:`smtplib` for sending mail::
  127. >>> from urllib.request import urlopen
  128. >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
  129. ... for line in response:
  130. ... line = line.decode('utf-8') # Decoding the binary data to text.
  131. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time
  132. ... print(line)
  133. <BR>Nov. 25, 09:43:32 PM EST
  134. >>> import smtplib
  135. >>> server = smtplib.SMTP('localhost')
  136. >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
  137. ... """To: jcaesar@example.org
  138. ... From: soothsayer@example.org
  139. ...
  140. ... Beware the Ides of March.
  141. ... """)
  142. >>> server.quit()
  143. (Note that the second example needs a mailserver running on localhost.)
  144. .. _tut-dates-and-times:
  145. Dates and Times
  146. ===============
  147. The :mod:`datetime` module supplies classes for manipulating dates and times in
  148. both simple and complex ways. While date and time arithmetic is supported, the
  149. focus of the implementation is on efficient member extraction for output
  150. formatting and manipulation. The module also supports objects that are timezone
  151. aware. ::
  152. >>> # dates are easily constructed and formatted
  153. >>> from datetime import date
  154. >>> now = date.today()
  155. >>> now
  156. datetime.date(2003, 12, 2)
  157. >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
  158. '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
  159. >>> # dates support calendar arithmetic
  160. >>> birthday = date(1964, 7, 31)
  161. >>> age = now - birthday
  162. >>> age.days
  163. 14368
  164. .. _tut-data-compression:
  165. Data Compression
  166. ================
  167. Common data archiving and compression formats are directly supported by modules
  168. including: :mod:`zlib`, :mod:`gzip`, :mod:`bz2`, :mod:`lzma`, :mod:`zipfile` and
  169. :mod:`tarfile`. ::
  170. >>> import zlib
  171. >>> s = b'witch which has which witches wrist watch'
  172. >>> len(s)
  173. 41
  174. >>> t = zlib.compress(s)
  175. >>> len(t)
  176. 37
  177. >>> zlib.decompress(t)
  178. b'witch which has which witches wrist watch'
  179. >>> zlib.crc32(s)
  180. 226805979
  181. .. _tut-performance-measurement:
  182. Performance Measurement
  183. =======================
  184. Some Python users develop a deep interest in knowing the relative performance of
  185. different approaches to the same problem. Python provides a measurement tool
  186. that answers those questions immediately.
  187. For example, it may be tempting to use the tuple packing and unpacking feature
  188. instead of the traditional approach to swapping arguments. The :mod:`timeit`
  189. module quickly demonstrates a modest performance advantage::
  190. >>> from timeit import Timer
  191. >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
  192. 0.57535828626024577
  193. >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
  194. 0.54962537085770791
  195. In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile` and
  196. :mod:`pstats` modules provide tools for identifying time critical sections in
  197. larger blocks of code.
  198. .. _tut-quality-control:
  199. Quality Control
  200. ===============
  201. One approach for developing high quality software is to write tests for each
  202. function as it is developed and to run those tests frequently during the
  203. development process.
  204. The :mod:`doctest` module provides a tool for scanning a module and validating
  205. tests embedded in a program's docstrings. Test construction is as simple as
  206. cutting-and-pasting a typical call along with its results into the docstring.
  207. This improves the documentation by providing the user with an example and it
  208. allows the doctest module to make sure the code remains true to the
  209. documentation::
  210. def average(values):
  211. """Computes the arithmetic mean of a list of numbers.
  212. >>> print(average([20, 30, 70]))
  213. 40.0
  214. """
  215. return sum(values) / len(values)
  216. import doctest
  217. doctest.testmod() # automatically validate the embedded tests
  218. The :mod:`unittest` module is not as effortless as the :mod:`doctest` module,
  219. but it allows a more comprehensive set of tests to be maintained in a separate
  220. file::
  221. import unittest
  222. class TestStatisticalFunctions(unittest.TestCase):
  223. def test_average(self):
  224. self.assertEqual(average([20, 30, 70]), 40.0)
  225. self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
  226. with self.assertRaises(ZeroDivisionError):
  227. average([])
  228. with self.assertRaises(TypeError):
  229. average(20, 30, 70)
  230. unittest.main() # Calling from the command line invokes all tests
  231. .. _tut-batteries-included:
  232. Batteries Included
  233. ==================
  234. Python has a "batteries included" philosophy. This is best seen through the
  235. sophisticated and robust capabilities of its larger packages. For example:
  236. * The :mod:`xmlrpc.client` and :mod:`xmlrpc.server` modules make implementing
  237. remote procedure calls into an almost trivial task. Despite the modules
  238. names, no direct knowledge or handling of XML is needed.
  239. * The :mod:`email` package is a library for managing email messages, including
  240. MIME and other :rfc:`2822`-based message documents. Unlike :mod:`smtplib` and
  241. :mod:`poplib` which actually send and receive messages, the email package has
  242. a complete toolset for building or decoding complex message structures
  243. (including attachments) and for implementing internet encoding and header
  244. protocols.
  245. * The :mod:`json` package provides robust support for parsing this
  246. popular data interchange format. The :mod:`csv` module supports
  247. direct reading and writing of files in Comma-Separated Value format,
  248. commonly supported by databases and spreadsheets. XML processing is
  249. supported by the :mod:`xml.etree.ElementTree`, :mod:`xml.dom` and
  250. :mod:`xml.sax` packages. Together, these modules and packages
  251. greatly simplify data interchange between Python applications and
  252. other tools.
  253. * The :mod:`sqlite3` module is a wrapper for the SQLite database
  254. library, providing a persistent database that can be updated and
  255. accessed using slightly nonstandard SQL syntax.
  256. * Internationalization is supported by a number of modules including
  257. :mod:`gettext`, :mod:`locale`, and the :mod:`codecs` package.