Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9ee0f7e

Browse files
khanhnnvngitbook-bot
authored andcommitted
GitBook: [master] 4 pages modified
1 parent 42ecd87 commit 9ee0f7e

4 files changed

Lines changed: 1147 additions & 1 deletion

File tree

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

0 commit comments

Comments
 (0)