“Python/docs/3.9/tutorial/stdlib”的版本间差异

来自菜鸟教程
Python/docs/3.9/tutorial/stdlib
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:10. 标准库简介 — Python 文档}}
 
<div id="brief-tour-of-the-standard-library" class="section">
 
<div id="brief-tour-of-the-standard-library" class="section">
  
 
<span id="tut-brieftour"></span>
 
<span id="tut-brieftour"></span>
= <span class="section-number">10. </span>Brief Tour of the Standard Library =
+
= 10. 标准库简介 =
  
 
<div id="operating-system-interface" class="section">
 
<div id="operating-system-interface" class="section">
  
 
<span id="tut-os-interface"></span>
 
<span id="tut-os-interface"></span>
== <span class="section-number">10.1. </span>Operating System Interface ==
+
== 10.1. 操作系统界面 ==
  
The [[../../library/os#module-os|<code>os</code>]] module provides dozens of functions for interacting with the
+
[[../../library/os#module-os|os]] 模块提供了几十个与操作系统交互的函数:
operating system:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第16行: 第16行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import os
+
<syntaxhighlight lang="python3">>>> import os
&gt;&gt;&gt; os.getcwd()      # Return the current working directory
+
>>> os.getcwd()      # Return the current working directory
 
'C:\\Python39'
 
'C:\\Python39'
&gt;&gt;&gt; os.chdir('/server/accesslogs')  # Change current working directory
+
>>> os.chdir('/server/accesslogs')  # Change current working directory
&gt;&gt;&gt; os.system('mkdir today')  # Run the command mkdir in the system shell
+
>>> os.system('mkdir today')  # Run the command mkdir in the system shell
0</pre>
+
0</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Be sure to use the <code>import os</code> style instead of <code>from os import *</code>. This
+
请务必使用 <code>import os</code> 样式而不是 <code>from os import *</code>。 这将防止 [[../../library/os#os|os.open()]] 隐藏内置的 [[../../library/functions#open|open()]] 函数,该函数的运行方式大不相同。
will keep [[../../library/os#os|<code>os.open()</code>]] from shadowing the built-in [[../../library/functions#open|<code>open()</code>]] function which
 
operates much differently.
 
  
The built-in [[../../library/functions#dir|<code>dir()</code>]] and [[../../library/functions#help|<code>help()</code>]] functions are useful as interactive
+
内置的 [[../../library/functions#dir|dir()]] [[../../library/functions#help|help()]] 函数可用作处理大型模块(如 [[../../library/os#module-os|os]])的交互式辅助工具:
aids for working with large modules like [[../../library/os#module-os|<code>os</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第37行: 第34行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import os
+
<syntaxhighlight lang="python3">>>> import os
&gt;&gt;&gt; dir(os)
+
>>> dir(os)
&lt;returns a list of all module functions&gt;
+
<returns a list of all module functions>
&gt;&gt;&gt; help(os)
+
>>> help(os)
&lt;returns an extensive manual page created from the module's docstrings&gt;</pre>
+
<returns an extensive manual page created from the module's docstrings></syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For daily file and directory management tasks, the [[../../library/shutil#module-shutil|<code>shutil</code>]] module provides
+
对于日常文件和目录管理任务,[[../../library/shutil#module-shutil|shutil]] 模块提供了更易于使用的更高级别的接口:
a higher level interface that is easier to use:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第53行: 第49行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import shutil
+
<syntaxhighlight lang="python3">>>> import shutil
&gt;&gt;&gt; shutil.copyfile('data.db', 'archive.db')
+
>>> shutil.copyfile('data.db', 'archive.db')
 
'archive.db'
 
'archive.db'
&gt;&gt;&gt; shutil.move('/build/executables', 'installdir')
+
>>> shutil.move('/build/executables', 'installdir')
'installdir'</pre>
+
'installdir'</syntaxhighlight>
  
 
</div>
 
</div>
第67行: 第63行:
  
 
<span id="tut-file-wildcards"></span>
 
<span id="tut-file-wildcards"></span>
== <span class="section-number">10.2. </span>File Wildcards ==
+
== 10.2. 文件通配符 ==
  
The [[../../library/glob#module-glob|<code>glob</code>]] module provides a function for making file lists from directory
+
[[../../library/glob#module-glob|glob]] 模块提供了从目录通配符搜索中生成文件列表的功能:
wildcard searches:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第76行: 第71行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import glob
+
<syntaxhighlight lang="python3">>>> import glob
&gt;&gt;&gt; glob.glob('*.py')
+
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']</pre>
+
['primes.py', 'random.py', 'quote.py']</syntaxhighlight>
  
 
</div>
 
</div>
第88行: 第83行:
  
 
<span id="tut-command-line-arguments"></span>
 
<span id="tut-command-line-arguments"></span>
== <span class="section-number">10.3. </span>Command Line Arguments ==
+
== 10.3. 命令行参数 ==
  
Common utility scripts often need to process command line arguments. These
+
通用实用程序脚本通常需要处理命令行参数。 这些参数作为列表存储在 [[../../library/sys#module-sys|sys]] 模块的 ''argv'' 属性中。 例如,在命令行运行 <code>python demo.py one two three</code> 会产生以下输出:
arguments are stored in the [[../../library/sys#module-sys|<code>sys</code>]] module's ''argv'' attribute as a list. For
 
instance the following output results from running <code>python demo.py one two three</code> at the command line:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第98行: 第91行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import sys
+
<syntaxhighlight lang="python3">>>> import sys
&gt;&gt;&gt; print(sys.argv)
+
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']</pre>
+
['demo.py', 'one', 'two', 'three']</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[../../library/argparse#module-argparse|<code>argparse</code>]] module provides a more sophisticated mechanism to process
+
[[../../library/argparse#module-argparse|argparse]] 模块提供了一种更复杂的机制来处理命令行参数。 以下脚本提取一个或多个文件名以及可选的要显示的行数:
command line arguments. The following script extracts one or more filenames
 
and an optional number of lines to be displayed:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第113行: 第104行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import argparse
+
<syntaxhighlight lang="python3">import argparse
  
 
parser = argparse.ArgumentParser(prog = 'top',
 
parser = argparse.ArgumentParser(prog = 'top',
第120行: 第111行:
 
parser.add_argument('-l', '--lines', type=int, default=10)
 
parser.add_argument('-l', '--lines', type=int, default=10)
 
args = parser.parse_args()
 
args = parser.parse_args()
print(args)</pre>
+
print(args)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
When run at the command line with <code>python top.py --lines=5 alpha.txt beta.txt</code>, the script sets <code>args.lines</code> to <code>5</code> and <code>args.filenames</code>
+
在命令行中使用 <code>python top.py --lines=5 alpha.txt beta.txt</code> 运行时,脚本将 <code>args.lines</code> 设置为 <code>5</code>,将 <code>args.filenames</code> 设置为 <code>['alpha.txt', 'beta.txt']</code>
to <code>['alpha.txt', 'beta.txt']</code>.
 
  
  
第133行: 第123行:
  
 
<span id="tut-stderr"></span>
 
<span id="tut-stderr"></span>
== <span class="section-number">10.4. </span>Error Output Redirection and Program Termination ==
+
== 10.4. 错误输出重定向和程序终止 ==
  
The [[../../library/sys#module-sys|<code>sys</code>]] module also has attributes for ''stdin'', ''stdout'', and ''stderr''.
+
[[../../library/sys#module-sys|sys]] 模块还具有 ''stdin''''stdout'' ''stderr'' 的属性。 后者对于发出警告和错误消息很有用,即使 ''stdout'' 已被重定向,也可以使它们可见:
The latter is useful for emitting warnings and error messages to make them
 
visible even when ''stdout'' has been redirected:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第143行: 第131行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; sys.stderr.write('Warning, log file not found starting a new one\n')
+
<syntaxhighlight lang="python3">>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one</pre>
+
Warning, log file not found starting a new one</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The most direct way to terminate a script is to use <code>sys.exit()</code>.
+
终止脚本的最直接方法是使用 <code>sys.exit()</code>
  
  
第156行: 第144行:
  
 
<span id="tut-string-pattern-matching"></span>
 
<span id="tut-string-pattern-matching"></span>
== <span class="section-number">10.5. </span>String Pattern Matching ==
+
== 10.5. 字符串模式匹配 ==
  
The [[../../library/re#module-re|<code>re</code>]] module provides regular expression tools for advanced string
+
[[../../library/re#module-re|re]] 模块为高级字符串处理提供了正则表达式工具。 对于复杂的匹配和操作,正则表达式提供了简洁、优化的解决方案:
processing. For complex matching and manipulation, regular expressions offer
 
succinct, optimized solutions:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第166行: 第152行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import re
+
<syntaxhighlight lang="python3">>>> import re
&gt;&gt;&gt; re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
+
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
 
['foot', 'fell', 'fastest']
 
['foot', 'fell', 'fastest']
&gt;&gt;&gt; re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
+
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'</pre>
+
'cat in the hat'</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
When only simple capabilities are needed, string methods are preferred because
+
当只需要简单的功能时,首选字符串方法,因为它们更易于阅读和调试:
they are easier to read and debug:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第182行: 第167行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; 'tea for too'.replace('too', 'two')
+
<syntaxhighlight lang="python3">>>> 'tea for too'.replace('too', 'two')
'tea for two'</pre>
+
'tea for two'</syntaxhighlight>
  
 
</div>
 
</div>
第193行: 第178行:
  
 
<span id="tut-mathematics"></span>
 
<span id="tut-mathematics"></span>
== <span class="section-number">10.6. </span>Mathematics ==
+
== 10.6. 数学 ==
  
The [[../../library/math#module-math|<code>math</code>]] module gives access to the underlying C library functions for
+
[[../../library/math#module-math|math]] 模块可以访问浮点数学的底层 C 库函数:
floating point math:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第202行: 第186行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import math
+
<syntaxhighlight lang="python3">>>> import math
&gt;&gt;&gt; math.cos(math.pi / 4)
+
>>> math.cos(math.pi / 4)
 
0.70710678118654757
 
0.70710678118654757
&gt;&gt;&gt; math.log(1024, 2)
+
>>> math.log(1024, 2)
10.0</pre>
+
10.0</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[../../library/random#module-random|<code>random</code>]] module provides tools for making random selections:
+
[[../../library/random#module-random|random]] 模块提供了进行随机选择的工具:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第217行: 第201行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import random
+
<syntaxhighlight lang="python3">>>> import random
&gt;&gt;&gt; random.choice(['apple', 'pear', 'banana'])
+
>>> random.choice(['apple', 'pear', 'banana'])
 
'apple'
 
'apple'
&gt;&gt;&gt; random.sample(range(100), 10)  # sampling without replacement
+
>>> random.sample(range(100), 10)  # sampling without replacement
 
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
 
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
&gt;&gt;&gt; random.random()    # random float
+
>>> random.random()    # random float
 
0.17970987693706186
 
0.17970987693706186
&gt;&gt;&gt; random.randrange(6)    # random integer chosen from range(6)
+
>>> random.randrange(6)    # random integer chosen from range(6)
4</pre>
+
4</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[../../library/statistics#module-statistics|<code>statistics</code>]] module calculates basic statistical properties
+
[[../../library/statistics#module-statistics|statistics]] 模块计算数值数据的基本统计属性(均值、中位数、方差等):
(the mean, median, variance, etc.) of numeric data:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第237行: 第220行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import statistics
+
<syntaxhighlight lang="python3">>>> import statistics
&gt;&gt;&gt; data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
+
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
&gt;&gt;&gt; statistics.mean(data)
+
>>> statistics.mean(data)
 
1.6071428571428572
 
1.6071428571428572
&gt;&gt;&gt; statistics.median(data)
+
>>> statistics.median(data)
 
1.25
 
1.25
&gt;&gt;&gt; statistics.variance(data)
+
>>> statistics.variance(data)
1.3720238095238095</pre>
+
1.3720238095238095</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The SciPy project &lt;https://scipy.org&gt; has many other modules for numerical
+
SciPy 项目 &lt; https://scipy.org &gt; 有许多其他的数值计算模块。
computations.
 
  
  
第257行: 第239行:
  
 
<span id="tut-internet-access"></span>
 
<span id="tut-internet-access"></span>
== <span class="section-number">10.7. </span>Internet Access ==
+
== 10.7. 互联网 ==
  
There are a number of modules for accessing the internet and processing internet
+
有许多用于访问互联网和处理互联网协议的模块。 两个最简单的是 [[../../library/urllib.request#module-urllib|urllib.request]] 用于从 URL 检索数据和 [[../../library/smtplib#module-smtplib|smtplib]] 用于发送邮件:
protocols. Two of the simplest are [[../../library/urllib.request#module-urllib|<code>urllib.request</code>]] for retrieving data
 
from URLs and [[../../library/smtplib#module-smtplib|<code>smtplib</code>]] for sending mail:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第267行: 第247行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; from urllib.request import urlopen
+
<syntaxhighlight lang="python3">>>> from urllib.request import urlopen
&gt;&gt;&gt; with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
+
>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
 
...    for line in response:
 
...    for line in response:
 
...        line = line.decode('utf-8')  # Decoding the binary data to text.
 
...        line = line.decode('utf-8')  # Decoding the binary data to text.
第274行: 第254行:
 
...            print(line)
 
...            print(line)
  
&lt;BR&gt;Nov. 25, 09:43:32 PM EST
+
<BR>Nov. 25, 09:43:32 PM EST
  
&gt;&gt;&gt; import smtplib
+
>>> import smtplib
&gt;&gt;&gt; server = smtplib.SMTP('localhost')
+
>>> server = smtplib.SMTP('localhost')
&gt;&gt;&gt; server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
+
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... &quot;&quot;&quot;To: jcaesar@example.org
+
... """To: jcaesar@example.org
 
... From: soothsayer@example.org
 
... From: soothsayer@example.org
 
...
 
...
 
... Beware the Ides of March.
 
... Beware the Ides of March.
... &quot;&quot;&quot;)
+
... """)
&gt;&gt;&gt; server.quit()</pre>
+
>>> server.quit()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
(Note that the second example needs a mailserver running on localhost.)
+
(请注意,第二个示例需要在本地主机上运行的邮件服务器。)
  
  
第296行: 第276行:
  
 
<span id="tut-dates-and-times"></span>
 
<span id="tut-dates-and-times"></span>
== <span class="section-number">10.8. </span>Dates and Times ==
+
== 10.8. 日期和时间 ==
  
The [[../../library/datetime#module-datetime|<code>datetime</code>]] module supplies classes for manipulating dates and times in
+
[[../../library/datetime#module-datetime|datetime]] 模块提供了以简单和复杂方式操作日期和时间的类。 虽然支持日期和时间算术,但实现的重点是高效的成员提取以进行输出格式化和操作。 该模块还支持时区感知的对象。
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.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第308行: 第284行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; # dates are easily constructed and formatted
+
<syntaxhighlight lang="python3">>>> # dates are easily constructed and formatted
&gt;&gt;&gt; from datetime import date
+
>>> from datetime import date
&gt;&gt;&gt; now = date.today()
+
>>> now = date.today()
&gt;&gt;&gt; now
+
>>> now
 
datetime.date(2003, 12, 2)
 
datetime.date(2003, 12, 2)
&gt;&gt;&gt; now.strftime(&quot;%m-%d-%y. %d %b %Y is a %A on the %d day of %B.&quot;)
+
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
 
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
 
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
  
&gt;&gt;&gt; # dates support calendar arithmetic
+
>>> # dates support calendar arithmetic
&gt;&gt;&gt; birthday = date(1964, 7, 31)
+
>>> birthday = date(1964, 7, 31)
&gt;&gt;&gt; age = now - birthday
+
>>> age = now - birthday
&gt;&gt;&gt; age.days
+
>>> age.days
14368</pre>
+
14368</syntaxhighlight>
  
 
</div>
 
</div>
第330行: 第306行:
  
 
<span id="tut-data-compression"></span>
 
<span id="tut-data-compression"></span>
== <span class="section-number">10.9. </span>Data Compression ==
+
== 10.9. 数据压缩 ==
  
Common data archiving and compression formats are directly supported by modules
+
常用的数据归档和压缩格式由模块直接支持,包括:[[../../library/zlib#module-zlib|zlib]][[../../library/gzip#module-gzip|gzip]][[../../library/bz2#module-bz2|bz2]][[../../library/lzma#module-lzma|lzma]]、zipfile[ X161X] [[../../library/tarfile#module-tarfile|tarfile]]
including: [[../../library/zlib#module-zlib|<code>zlib</code>]], [[../../library/gzip#module-gzip|<code>gzip</code>]], [[../../library/bz2#module-bz2|<code>bz2</code>]], [[../../library/lzma#module-lzma|<code>lzma</code>]], [[../../library/zipfile#module-zipfile|<code>zipfile</code>]] and
 
[[../../library/tarfile#module-tarfile|<code>tarfile</code>]].
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第340行: 第314行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import zlib
+
<syntaxhighlight lang="python3">>>> import zlib
&gt;&gt;&gt; s = b'witch which has which witches wrist watch'
+
>>> s = b'witch which has which witches wrist watch'
&gt;&gt;&gt; len(s)
+
>>> len(s)
 
41
 
41
&gt;&gt;&gt; t = zlib.compress(s)
+
>>> t = zlib.compress(s)
&gt;&gt;&gt; len(t)
+
>>> len(t)
 
37
 
37
&gt;&gt;&gt; zlib.decompress(t)
+
>>> zlib.decompress(t)
 
b'witch which has which witches wrist watch'
 
b'witch which has which witches wrist watch'
&gt;&gt;&gt; zlib.crc32(s)
+
>>> zlib.crc32(s)
226805979</pre>
+
226805979</syntaxhighlight>
  
 
</div>
 
</div>
第360行: 第334行:
  
 
<span id="tut-performance-measurement"></span>
 
<span id="tut-performance-measurement"></span>
== <span class="section-number">10.10. </span>Performance Measurement ==
+
== 10.10. 绩效衡量 ==
  
Some Python users develop a deep interest in knowing the relative performance of
+
一些 Python 用户对了解解决同一问题的不同方法的相对性能产生了浓厚的兴趣。 Python 提供了一种测量工具,可以立即回答这些问题。
different approaches to the same problem. Python provides a measurement tool
 
that answers those questions immediately.
 
  
For example, it may be tempting to use the tuple packing and unpacking feature
+
例如,使用元组打包和解包功能而不是传统的方法来交换参数可能很诱人。 [[../../library/timeit#module-timeit|timeit]] 模块迅速展示了适度的性能优势:
instead of the traditional approach to swapping arguments. The [[../../library/timeit#module-timeit|<code>timeit</code>]]
 
module quickly demonstrates a modest performance advantage:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第374行: 第344行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; from timeit import Timer
+
<syntaxhighlight lang="python3">>>> from timeit import Timer
&gt;&gt;&gt; Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
+
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
 
0.57535828626024577
 
0.57535828626024577
&gt;&gt;&gt; Timer('a,b = b,a', 'a=1; b=2').timeit()
+
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791</pre>
+
0.54962537085770791</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
In contrast to [[../../library/timeit#module-timeit|<code>timeit</code>]]'s fine level of granularity, the [[../../library/profile#module-profile|<code>profile</code>]] and
+
[[../../library/timeit#module-timeit|timeit]] 的精细粒度级别相比,[[../../library/profile#module-profile|profile]] [[../../library/profile#module-pstats|pstats]] 模块提供了用于识别较大代码块中的时间关键部分的工具。
[[../../library/profile#module-pstats|<code>pstats</code>]] modules provide tools for identifying time critical sections in
 
larger blocks of code.
 
  
  
第392行: 第360行:
  
 
<span id="tut-quality-control"></span>
 
<span id="tut-quality-control"></span>
== <span class="section-number">10.11. </span>Quality Control ==
+
== 10.11. 质量控制 ==
  
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.
 
  
The [[../../library/doctest#module-doctest|<code>doctest</code>]] module provides a tool for scanning a module and validating
+
[[../../library/doctest#module-doctest|doctest]] 模块提供了一个用于扫描模块和验证嵌入在程序文档字符串中的测试的工具。 测试构建就像将典型调用及其结果剪切并粘贴到文档字符串中一样简单。 这通过为用户提供示例来改进文档,并允许 doctest 模块确保代码与文档保持一致:
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:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第409行: 第370行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def average(values):
+
<syntaxhighlight lang="python3">def average(values):
     &quot;&quot;&quot;Computes the arithmetic mean of a list of numbers.
+
     """Computes the arithmetic mean of a list of numbers.
  
     &gt;&gt;&gt; print(average([20, 30, 70]))
+
     >>> print(average([20, 30, 70]))
 
     40.0
 
     40.0
     &quot;&quot;&quot;
+
     """
 
     return sum(values) / len(values)
 
     return sum(values) / len(values)
  
 
import doctest
 
import doctest
doctest.testmod()  # automatically validate the embedded tests</pre>
+
doctest.testmod()  # automatically validate the embedded tests</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[../../library/unittest#module-unittest|<code>unittest</code>]] module is not as effortless as the [[../../library/doctest#module-doctest|<code>doctest</code>]] module,
+
[[../../library/unittest#module-unittest|unittest]] 模块不像 [[../../library/doctest#module-doctest|doctest]] 模块那么轻松,但它允许在单独的文件中维护一组更全面的测试:
but it allows a more comprehensive set of tests to be maintained in a separate
 
file:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第431行: 第390行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import unittest
+
<syntaxhighlight lang="python3">import unittest
  
 
class TestStatisticalFunctions(unittest.TestCase):
 
class TestStatisticalFunctions(unittest.TestCase):
第443行: 第402行:
 
             average(20, 30, 70)
 
             average(20, 30, 70)
  
unittest.main()  # Calling from the command line invokes all tests</pre>
+
unittest.main()  # Calling from the command line invokes all tests</syntaxhighlight>
  
 
</div>
 
</div>
第453行: 第412行:
  
 
<span id="tut-batteries-included"></span>
 
<span id="tut-batteries-included"></span>
== <span class="section-number">10.12. </span>Batteries Included ==
+
== 10.12. 包括电池 ==
  
Python has a &quot;batteries included&quot; philosophy. This is best seen through the
+
Python 有一个“包含电池”的理念。 通过其较大封装的复杂和强大功能可以最好地看出这一点。 例如:
sophisticated and robust capabilities of its larger packages. For example:
 
  
* The [[../../library/xmlrpc.client#module-xmlrpc|<code>xmlrpc.client</code>]] and [[../../library/xmlrpc.server#module-xmlrpc|<code>xmlrpc.server</code>]] modules make implementing remote procedure calls into an almost trivial task. Despite the modules names, no direct knowledge or handling of XML is needed.
+
* [[../../library/xmlrpc.client#module-xmlrpc|xmlrpc.client]] [[../../library/xmlrpc.server#module-xmlrpc|xmlrpc.server]] 模块使实现远程过程调用成为一项几乎微不足道的任务。 尽管有模块名称,但不需要直接了解或处理 XML。
* The [[../../library/email#module-email|<code>email</code>]] package is a library for managing email messages, including MIME and other <span id="index-1" class="target"></span>[https://tools.ietf.org/html/rfc2822.html '''RFC 2822''']-based message documents. Unlike [[../../library/smtplib#module-smtplib|<code>smtplib</code>]] and [[../../library/poplib#module-poplib|<code>poplib</code>]] 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.
+
* [[../../library/email#module-email|email]] 包是一个用于管理电子邮件消息的库,包括 MIME 和其他基于 <span id="index-1" class="target"></span>[https://tools.ietf.org/html/rfc2822.html RFC 2822] 的消息文档。 与实际发送和接收消息的 [[../../library/smtplib#module-smtplib|smtplib]] [[../../library/poplib#module-poplib|poplib]] 不同,电子邮件包具有用于构建或解码复杂消息结构(包括附件)以及用于实现 Internet 编码和标头协议的完整工具集。
* The [[../../library/json#module-json|<code>json</code>]] package provides robust support for parsing this popular data interchange format. The [[../../library/csv#module-csv|<code>csv</code>]] 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 [[../../library/xml.etree.elementtree#module-xml.etree|<code>xml.etree.ElementTree</code>]], [[../../library/xml.dom#module-xml|<code>xml.dom</code>]] and [[../../library/xml.sax#module-xml|<code>xml.sax</code>]] packages. Together, these modules and packages greatly simplify data interchange between Python applications and other tools.
+
* [[../../library/json#module-json|json]] 包为解析这种流行的数据交换格式提供了强大的支持。 [[../../library/csv#module-csv|csv]]模块支持直接读写逗号分隔值格式的文件,数据库和电子表格常用。 [[../../library/xml.etree.elementtree#module-xml.etree|xml.etree.ElementTree]][[../../library/xml.dom#module-xml|xml.dom]] [[../../library/xml.sax#module-xml|xml.sax]] 包支持 XML 处理。 这些模块和包一起极大地简化了 Python 应用程序和其他工具之间的数据交换。
* The [[../../library/sqlite3#module-sqlite3|<code>sqlite3</code>]] module is a wrapper for the SQLite database library, providing a persistent database that can be updated and accessed using slightly nonstandard SQL syntax.
+
* [[../../library/sqlite3#module-sqlite3|sqlite3]] 模块是 SQLite 数据库库的包装器,提供了一个可以使用稍微非标准的 SQL 语法更新和访问的持久数据库。
* Internationalization is supported by a number of modules including [[../../library/gettext#module-gettext|<code>gettext</code>]], [[../../library/locale#module-locale|<code>locale</code>]], and the [[../../library/codecs#module-codecs|<code>codecs</code>]] package.
+
* 许多模块支持国际化,包括 [[../../library/gettext#module-gettext|gettext]][[../../library/locale#module-locale|locale]] [[../../library/codecs#module-codecs|codecs]] 包。
  
  
第468行: 第426行:
  
 
</div>
 
</div>
 +
<div class="clearer">
  
[[Category:Python 3.9 中文文档]]
+
 
 +
 
 +
</div>
 +
 
 +
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:54的最新版本

10. 标准库简介

10.1. 操作系统界面

os 模块提供了几十个与操作系统交互的函数:

>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python39'
>>> os.chdir('/server/accesslogs')   # Change current working directory
>>> os.system('mkdir today')   # Run the command mkdir in the system shell
0

请务必使用 import os 样式而不是 from os import *。 这将防止 os.open() 隐藏内置的 open() 函数,该函数的运行方式大不相同。

内置的 dir()help() 函数可用作处理大型模块(如 os)的交互式辅助工具:

>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>

对于日常文件和目录管理任务,shutil 模块提供了更易于使用的更高级别的接口:

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'

10.2. 文件通配符

glob 模块提供了从目录通配符搜索中生成文件列表的功能:

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

10.3. 命令行参数

通用实用程序脚本通常需要处理命令行参数。 这些参数作为列表存储在 sys 模块的 argv 属性中。 例如,在命令行运行 python demo.py one two three 会产生以下输出:

>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']

argparse 模块提供了一种更复杂的机制来处理命令行参数。 以下脚本提取一个或多个文件名以及可选的要显示的行数:

import argparse

parser = argparse.ArgumentParser(prog = 'top',
    description = 'Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)

在命令行中使用 python top.py --lines=5 alpha.txt beta.txt 运行时,脚本将 args.lines 设置为 5,将 args.filenames 设置为 ['alpha.txt', 'beta.txt']


10.4. 错误输出重定向和程序终止

sys 模块还具有 stdinstdoutstderr 的属性。 后者对于发出警告和错误消息很有用,即使 stdout 已被重定向,也可以使它们可见:

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

终止脚本的最直接方法是使用 sys.exit()


10.5. 字符串模式匹配

re 模块为高级字符串处理提供了正则表达式工具。 对于复杂的匹配和操作,正则表达式提供了简洁、优化的解决方案:

>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

当只需要简单的功能时,首选字符串方法,因为它们更易于阅读和调试:

>>> 'tea for too'.replace('too', 'two')
'tea for two'

10.6. 数学

math 模块可以访问浮点数学的底层 C 库函数:

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

random 模块提供了进行随机选择的工具:

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

statistics 模块计算数值数据的基本统计属性(均值、中位数、方差等):

>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095

SciPy 项目 < https://scipy.org > 有许多其他的数值计算模块。


10.7. 互联网

有许多用于访问互联网和处理互联网协议的模块。 两个最简单的是 urllib.request 用于从 URL 检索数据和 smtplib 用于发送邮件:

>>> from urllib.request import urlopen
>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
...     for line in response:
...         line = line.decode('utf-8')  # Decoding the binary data to text.
...         if 'EST' in line or 'EDT' in line:  # look for Eastern Time
...             print(line)

<BR>Nov. 25, 09:43:32 PM EST

>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()

(请注意,第二个示例需要在本地主机上运行的邮件服务器。)


10.8. 日期和时间

datetime 模块提供了以简单和复杂方式操作日期和时间的类。 虽然支持日期和时间算术,但实现的重点是高效的成员提取以进行输出格式化和操作。 该模块还支持时区感知的对象。

>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368

10.9. 数据压缩

常用的数据归档和压缩格式由模块直接支持,包括:zlibgzipbz2lzma、zipfile[ X161X] 和 tarfile

>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

10.10. 绩效衡量

一些 Python 用户对了解解决同一问题的不同方法的相对性能产生了浓厚的兴趣。 Python 提供了一种测量工具,可以立即回答这些问题。

例如,使用元组打包和解包功能而不是传统的方法来交换参数可能很诱人。 timeit 模块迅速展示了适度的性能优势:

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

timeit 的精细粒度级别相比,profilepstats 模块提供了用于识别较大代码块中的时间关键部分的工具。


10.11. 质量控制

开发高质量软件的一种方法是在开发过程中为每个功能编写测试,并在开发过程中频繁运行这些测试。

doctest 模块提供了一个用于扫描模块和验证嵌入在程序文档字符串中的测试的工具。 测试构建就像将典型调用及其结果剪切并粘贴到文档字符串中一样简单。 这通过为用户提供示例来改进文档,并允许 doctest 模块确保代码与文档保持一致:

def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
doctest.testmod()   # automatically validate the embedded tests

unittest 模块不像 doctest 模块那么轻松,但它允许在单独的文件中维护一组更全面的测试:

import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20, 30, 70)

unittest.main()  # Calling from the command line invokes all tests

10.12. 包括电池

Python 有一个“包含电池”的理念。 通过其较大封装的复杂和强大功能可以最好地看出这一点。 例如:

  • xmlrpc.clientxmlrpc.server 模块使实现远程过程调用成为一项几乎微不足道的任务。 尽管有模块名称,但不需要直接了解或处理 XML。
  • email 包是一个用于管理电子邮件消息的库,包括 MIME 和其他基于 RFC 2822 的消息文档。 与实际发送和接收消息的 smtplibpoplib 不同,电子邮件包具有用于构建或解码复杂消息结构(包括附件)以及用于实现 Internet 编码和标头协议的完整工具集。
  • json 包为解析这种流行的数据交换格式提供了强大的支持。 csv模块支持直接读写逗号分隔值格式的文件,数据库和电子表格常用。 xml.etree.ElementTreexml.domxml.sax 包支持 XML 处理。 这些模块和包一起极大地简化了 Python 应用程序和其他工具之间的数据交换。
  • sqlite3 模块是 SQLite 数据库库的包装器,提供了一个可以使用稍微非标准的 SQL 语法更新和访问的持久数据库。
  • 许多模块支持国际化,包括 gettextlocalecodecs 包。