The os module provides dozens of functions for interacting with the operating system:
os 模塊提供了不少與操作系統(tǒng)相關(guān)聯(lián)的函數(shù)。
>>> import os >>> os.system('time 0:02') 0 >>> os.getcwd() # Return the current working directory 'C:\\Python24' >>> os.chdir('/server/accesslogs')
Be sure to use the "import os" style instead of "from os import *". This will keep os.open() from shadowing the builtin open() function which operates much differently.
應(yīng)該用 "import os" 風(fēng)格而非 "from os import *"。這樣可以保證隨操作系統(tǒng)不同而有所變化的 os.open() 不會(huì)覆蓋內(nèi)置函數(shù) open()。
The builtin dir() and help() functions are useful as interactive aids for working with large modules like os:
在使用一些像 os 這樣的大型模塊時(shí)內(nèi)置的 dir() 和 help() 函數(shù)非常有用。
>>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive manual page created from the module's docstrings>
For daily file and directory management tasks, the shutil module provides a higher level interface that is easier to use:
針對(duì)日常的文件和目錄管理任務(wù),shutil 模塊提供了一個(gè)易于使用的高級(jí)接口。
>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') >>> shutil.move('/build/executables', 'installdir')
The glob module provides a function for making file lists from directory wildcard searches:
glob 模塊提供了一個(gè)函數(shù)用于從目錄通配符搜索中生成文件列表。
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py']
Common utility scripts often invoke processing command line arguments. These arguments are stored in the sys module's argv attribute as a list. For instance the following output results from running "python demo.py one two three" at the command line:
通用工具腳本經(jīng)常調(diào)用命令行參數(shù)。這些命令行參數(shù)以鏈表形式存儲(chǔ)于 sys 模塊的 argv 變量。例如在命令行中執(zhí)行 "python demo.py one two three" 后可以得到以下輸出結(jié)果:
>>> import sys >>> print sys.argv ['demo.py', 'one', 'two', 'three']
The getopt module processes sys.argv using the conventions of the Unix getopt() function. More powerful and flexible command line processing is provided by the optparse module.
getopt 模塊使用 Unix getopt() 函處理 sys.argv。更多的復(fù)雜命令行處理由 optparse 模塊提供。
The 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:
sys 還有 stdin, stdout 和 stderr 屬性,即使在 stdout 被重定向時(shí),后者也可以用于顯示警告和錯(cuò)誤信息。
>>> sys.stderr.write('Warning, log file not found starting a new one') Warning, log file not found starting a new one
The most direct way to terminate a script is to use "sys.exit()".
大多腳本的定向終止都使用 "sys.exit()"。
The re module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions:
re 模塊為高級(jí)字符串處理提供了正則表達(dá)式工具。對(duì)于復(fù)雜的匹配和處理,正則表達(dá)式提供了簡(jiǎn)潔、優(yōu)化的解決方案。
>>> 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'
When only simple capabilities are needed, string methods are preferred because they are easier to read and debug:
如果只需要簡(jiǎn)單的功能,應(yīng)該首先考慮字符串方法,因?yàn)樗鼈兎浅:?jiǎn)單,易于閱讀和調(diào)試。
>>> 'tea for too'.replace('too', 'two') 'tea for two'
The math module gives access to the underlying C library functions for floating point math:
math 模塊為浮點(diǎn)運(yùn)算提供了對(duì)底層C函數(shù)庫(kù)的訪問(wèn)。
>>> import math >>> math.cos(math.pi / 4.0) 0.70710678118654757 >>> math.log(1024, 2) 10.0
The random module provides tools for making random selections:
random 提供了生成隨機(jī)數(shù)的工具。
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(xrange(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
There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are urllib2 for retrieving data from urls and smtplib for sending mail:
有幾個(gè)模塊用于訪問(wèn)互聯(lián)網(wǎng)以及處理網(wǎng)絡(luò)通信協(xié)議。其中最簡(jiǎn)單的兩個(gè)是用于處理從 urls 接收的數(shù)據(jù)的 urllib2 以及用于發(fā)送電子郵件的 smtplib。
>>> import urllib2 >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... if 'EST' in line: # look for Eastern Standard Time ... print line <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('soothsayer@tmp.org', 'jceasar@tmp.org', """To: jceasar@tmp.org From: soothsayer@tmp.org Beware the Ides of March. """) >>> server.quit()
The 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 time zone aware.
datetime 模塊為日期和時(shí)間處理同時(shí)提供了簡(jiǎn)單和復(fù)雜的方法。支持日期和時(shí)間算法的同時(shí),實(shí)現(xiàn)的重點(diǎn)放在更有效的處理和格式化輸出。該模塊還支持時(shí)區(qū)處理。
# dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y or %d%b %Y is a %A on the %d day of %B") '12-02-03 or 02Dec 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
Common data archiving and compression formats are directly supported by modules including: zlib, gzip, bz2, zipfile, and tarfile.
以下模塊直接支持通用的數(shù)據(jù)打包和壓縮格式:
zlib, gzip, bz2, zipfile, 以及 tarfile
>>> import zlib >>> s = 'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) 'witch which has which witches wrist watch' >>> zlib.crc32(t) -1438085031
Some Python users develop a deep interest in knowing the relative performance between different approaches to the same problem. Python provides a measurement tool that answers those questions immediately.
有些用戶對(duì)了解解決同一問(wèn)題的不同方法之間的性能差異很感興趣。Python 提供了一個(gè)度量工具,為這些問(wèn)題提供了直接答案。
For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments. The timeit module quickly demonstrates that the traditional approach is faster:
例如,使用元組封裝和拆封來(lái)交換元素看起來(lái)要比使用傳統(tǒng)的方法要誘人的多。timeit 證明了傳統(tǒng)的方法更快一些。
>>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.60864915603680925 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.8625194857439773
In contrast to timeit's fine level of granularity, the profile and pstats modules provide tools for identifying time critical sections in larger blocks of code.
相對(duì)于 timeit 的細(xì)粒度,profile 和 pstats 模塊提供了針對(duì)更大代碼塊的時(shí)間度量工具。
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.
開(kāi)發(fā)高質(zhì)量軟件的方法之一是為每一個(gè)函數(shù)開(kāi)發(fā)測(cè)試代碼,并且在開(kāi)發(fā)過(guò)程中經(jīng)常進(jìn)行測(cè)試。
The 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:
doctest 模塊提供了一個(gè)工具,掃描模塊并根據(jù)程序中內(nèi)嵌的文檔字符串執(zhí)行測(cè)試。測(cè)試構(gòu)造如同簡(jiǎn)單的將它的輸出結(jié)果剪切并粘貼到文檔字符串中。通過(guò)用戶提供的例子,它發(fā)展了文檔,允許 doctest 模塊確認(rèn)代碼的結(jié)果是否與文檔一致。
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 """ return sum(values, 0.0) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests
The unittest module is not as effortless as the doctest module, but it allows a more comprehensive set of tests to be maintained in a separate file:
unittest 模塊不像 doctest 模塊那么容易使用,不過(guò)它可以在一個(gè)獨(dú)立的文件里提供一個(gè)更全面的測(cè)試集。
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) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main() # Calling from the command line invokes all tests
Python has a ``batteries included'' philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example:
Python 體現(xiàn)了“batteries included”哲學(xué)。Python 可以通過(guò)更大的包的來(lái)得到應(yīng)付各種復(fù)雜情況的強(qiáng)大能力,從這一點(diǎn)我們可以看出該思想的應(yīng)用。例如:
* The xmlrpclib and SimpleXMLRPCServer modules make implementing remote procedure calls into an almost trivial task. Despite the names, no direct knowledge or handling of XML is needed.
* xmlrpclib 和 SimpleXMLRPCServer 模塊實(shí)現(xiàn)了在瑣碎的任務(wù)中調(diào)用遠(yuǎn)程過(guò)程。盡管有這樣的名字,其實(shí)用戶不需要直接處理 XML ,也不需要這方面的知識(shí)。
* The email package is a library for managing email messages, including MIME and other RFC 2822-based message documents. Unlike smtplib and 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.
* email 包是一個(gè)郵件消息管理庫(kù),可以處理 MIME 或其它基于 RFC 2822 的消息文檔。不同于實(shí)際發(fā)送和接收消息的 smtplib 和 poplib 模塊,email 包有一個(gè)用于構(gòu)建或解析復(fù)雜消息結(jié)構(gòu)(包括附件)以及實(shí)現(xiàn)互聯(lián)網(wǎng)編碼和頭協(xié)議的完整工具集。
* The xml.dom and xml.sax packages provide robust support for parsing this popular data interchange format. Likewise, the csv module supports direct reads and writes in a common database format. Together, these modules and packages greatly simplify data interchange between python applications and other tools.
* xml.dom 和 xml.sax 包為流行的信息交換格式提供了強(qiáng)大的支持。同樣, csv 模塊支持在通用數(shù)據(jù)庫(kù)格式中直接讀寫(xiě)。綜合起來(lái),這些模塊和包大大簡(jiǎn)化了 Python 應(yīng)用程序和其它工具之間的數(shù)據(jù)交換。
* Internationalization is supported by a number of modules including gettext, locale, and the codecs package.
* 國(guó)際化由 gettext, locale和 codecs 包支持。
譯者:劉鑫(march.liu AT gmail DOT com) 由:limodou轉(zhuǎn)(limodou AT gmail DOT com) CHM 文件制作:Colin.Wang 2007年9月