.. _tut-brieftour: ********************************** Python æ ‡å‡†åº“æ¦‚è§ˆ ********************************** .. _tut-os-interface: æ“ä½œç³»ç»ŸæŽ¥å£ ========================== `os <https://docs.python.org/2.7/library/os.html#module-os>`_ æ¨¡å—æä¾›äº†å¾ˆå¤šä¸Žæ“作系统交互的函数:: >>> import os >>> os.getcwd() # Return the current working directory 'C:\\Python27' >>> 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() <https://docs.python.org/2.7/library/os.html#os.open>`_ ä¸ä¼šè¦†ç›–内置函数 `open() <https://docs.python.org/2.7/library/functions.html#open>`_ .. index:: builtin: help åœ¨ä½¿ç”¨ä¸€äº›åƒ `os <https://docs.python.org/2.7/library/os.html#module-os>`_ è¿™æ ·çš„å¤§åž‹æ¨¡å—æ—¶å†…置的 `dir() <https://docs.python.org/2.7/library/functions.html#dir>`_ å’Œ `help() <https://docs.python.org/2.7/library/functions.html#help>`_ 函数éžå¸¸æœ‰ç”¨:: >>> 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 <https://docs.python.org/2.7/library/shutil.html#module-shutil>`_ æ¨¡å—æä¾›äº†ä¸€ä¸ªæ˜“äºŽä½¿ç”¨çš„é«˜çº§æŽ¥å£:: >>> import shutil >>> shutil.copyfile('data.db', 'archive.db') >>> shutil.move('/build/executables', 'installdir') .. _tut-file-wildcards: 文件通é…符 ============== `glob <https://docs.python.org/2.7/library/glob.html#module-glob>`_ æ¨¡å—æä¾›äº†ä¸€ä¸ªå‡½æ•°ç”¨äºŽä»Žç›®å½•é€šé…符æœç´¢ä¸ç”Ÿæˆæ–‡ä»¶åˆ—表:: >>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py'] .. _tut-command-line-arguments: å‘½ä»¤è¡Œå‚æ•° ====================== 通用工具脚本ç»å¸¸è°ƒç”¨å‘½ä»¤è¡Œå‚æ•°ã€‚è¿™äº›å‘½ä»¤è¡Œå‚æ•°ä»¥é“¾è¡¨å½¢å¼å˜å‚¨äºŽ `sys <https://docs.python.org/2.7/library/sys.html#module-sys>`_ 模å—çš„ *argv* å˜é‡ã€‚ä¾‹å¦‚åœ¨å‘½ä»¤è¡Œä¸æ‰§è¡Œ ``python demo.py one two three`` åŽå¯ä»¥å¾—到以下输出结果:: >>> import sys >>> print sys.argv ['demo.py', 'one', 'two', 'three'] `getopt <https://docs.python.org/2.7/library/getopt.html#module-getopt>`_ 模å—使用 Unix `getopt() <https://docs.python.org/2.7/library/getopt.html#module-getopt>`_ å‡½æ•°å¤„ç† *sys.argv*ã€‚æ›´å¤šçš„å¤æ‚命令行处ç†ç”± `argparse <https://docs.python.org/2.7/library/argparse.html#module-argparse>`_ æ¨¡å—æä¾›ã€‚ .. _tut-stderr: 错误输出é‡å®šå‘和程åºç»ˆæ¢ ================================================ `sys <https://docs.python.org/2.7/library/sys.html#module-sys>`_ 还有 *stdin*, *stdout* å’Œ *stderr* 属性,å³ä½¿åœ¨ *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()`` 。 .. _tut-string-pattern-matching: å—符串æ£åˆ™åŒ¹é… ======================= `re <https://docs.python.org/2.7/library/re.html#module-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' .. _tut-mathematics: æ•°å¦ =========== `math <https://docs.python.org/2.7/library/math.html#module-math>`_ 模å—为浮点è¿ç®—æä¾›äº†å¯¹åº•层 C 函数库的访问:: >>> import math >>> math.cos(math.pi / 4.0) 0.70710678118654757 >>> math.log(1024, 2) 10.0 `random <https://docs.python.org/2.7/library/random.html#module-random>`_ æä¾›äº†ç”Ÿæˆéšæœºæ•°çš„å·¥å…·:: >>> 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 .. _tut-internet-access: 互è”网访问 =============== æœ‰å‡ ä¸ªæ¨¡å—用于访问互è”网以åŠå¤„ç†ç½‘络通信åè®®ã€‚å…¶ä¸æœ€ç®€å•的两个是用于处ç†ä»Ž urls 接收的数æ®çš„ `urllib2 <https://docs.python.org/2.7/library/urllib2.html#module-urllib2>`_ 以åŠç”¨äºŽå‘é€ç”µå邮件的 `smtplib <https://docs.python.org/2.7/library/smtplib.html#module-smtplib>`_:: >>> import urllib2 >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... 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() (注æ„第二个例å需è¦åœ¨ localhost è¿è¡Œä¸€ä¸ªé‚®ä»¶æœåŠ¡å™¨ã€‚) .. _tut-dates-and-times: 日期和时间 =============== `datetime <https://docs.python.org/2.7/library/datetime.html#module-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 .. _tut-data-compression: æ•°æ®åŽ‹ç¼© ================ 以下模å—直接支æŒé€šç”¨çš„æ•°æ®æ‰“åŒ…å’ŒåŽ‹ç¼©æ ¼å¼ï¼š`zlib <https://docs.python.org/2.7/library/zlib.html#module-zlib>`_,`gzip <https://docs.python.org/2.7/library/gzip.html#module-gzip>`_,`bz2 <https://docs.python.org/2.7/library/bz2.html#module-bz2>`_,`zipfile <https://docs.python.org/2.7/library/zipfile.html#module-zipfile>`_ ä»¥åŠ `tarfile <https://docs.python.org/2.7/library/tarfile.html#module-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 .. _tut-performance-measurement: æ€§èƒ½åº¦é‡ ======================= 有些用户对了解解决åŒä¸€é—®é¢˜çš„ä¸åŒæ–¹æ³•之间的性能差异很感兴趣。Python æä¾›äº†ä¸€ä¸ªåº¦é‡å·¥å…·ï¼Œä¸ºè¿™äº›é—®é¢˜æä¾›äº†ç›´æŽ¥ç”案。 例如,使用元组å°è£…å’Œæ‹†å°æ¥äº¤æ¢å…ƒç´ 看起æ¥è¦æ¯”ä½¿ç”¨ä¼ ç»Ÿçš„æ–¹æ³•è¦è¯±äººçš„多。`timeit <https://docs.python.org/2.7/library/timeit.html#module-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 <https://docs.python.org/2.7/library/timeit.html#module-timeit>`_ 的细粒度,`profile <https://docs.python.org/2.7/library/profile.html#module-profile>`_ å’Œ `pstats <https://docs.python.org/2.7/library/profile.html#module-pstats>`_ æ¨¡å—æä¾›äº†é’ˆå¯¹æ›´å¤§ä»£ç å—的时间度é‡å·¥å…·ã€‚ .. _tut-quality-control: è´¨é‡æŽ§åˆ¶ =============== å¼€å‘高质é‡è½¯ä»¶çš„æ–¹æ³•之一是为æ¯ä¸€ä¸ªå‡½æ•°å¼€å‘测试代ç ,并且在开å‘过程ä¸ç»å¸¸è¿›è¡Œæµ‹è¯•。 `doctest <https://docs.python.org/2.7/library/doctest.html#module-doctest>`_ æ¨¡å—æä¾›äº†ä¸€ä¸ªå·¥å…·ï¼Œæ‰«ææ¨¡å—å¹¶æ ¹æ®ç¨‹åºä¸å†…嵌的文档å—ç¬¦ä¸²æ‰§è¡Œæµ‹è¯•ã€‚æµ‹è¯•æž„é€ å¦‚åŒç®€å•的将它的输出结果剪切并粘贴到文档å—符串ä¸ã€‚通过用户æä¾›çš„例å,它å‘展了文档,å…许 doctest 模å—确认代ç 的结果是å¦ä¸Žæ–‡æ¡£ä¸€è‡´:: 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 `unittest <https://docs.python.org/2.7/library/unittest.html#module-unittest>`_ 模å—ä¸åƒ `doctest <https://docs.python.org/2.7/library/doctest.html#module-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) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main() # Calling from the command line invokes all tests .. _tut-batteries-included: “瑞士军刀†================== Python 展现了“瑞士军刀â€çš„哲å¦ã€‚è¿™å¯ä»¥é€šè¿‡å®ƒæ›´å¤§çš„包的高级和å¥å£®çš„功能æ¥å¾—到最好的展现。例如: * `xmlrpclib <https://docs.python.org/2.7/library/xmlrpclib.html#module-xmlrpclib>`_ å’Œ `SimpleXMLRPCServer <https://docs.python.org/2.7/library/simplexmlrpcserver.html#module-SimpleXMLRPCServer>`_ 模å—让远程过程调用å˜å¾—轻而易举。 å°½ç®¡æ¨¡å—æœ‰è¿™æ ·çš„åå—ï¼Œç”¨æˆ·æ— éœ€æ‹¥æœ‰XMLçš„çŸ¥è¯†æˆ–å¤„ç† XML。 * `email <https://docs.python.org/2.7/library/email.html#module-email>`_ 包是一个管ç†é‚®ä»¶ä¿¡æ¯çš„库,包括MIME和其它基于 RFC2822 çš„ä¿¡æ¯æ–‡æ¡£ã€‚ ä¸åŒäºŽå®žé™…å‘é€å’ŒæŽ¥æ”¶ä¿¡æ¯çš„ `smtplib <https://docs.python.org/2.7/library/smtplib.html#module-smtplib>`_ å’Œ `poplib <https://docs.python.org/2.7/library/poplib.html#module-poplib>`_ 模å—,email 包包å«ä¸€ä¸ªæž„é€ æˆ–è§£æžå¤æ‚消æ¯ç»“æž„(包括附件)åŠå®žçŽ°äº’è”网编ç 和头å议的完整工具集。 * `xml.dom <https://docs.python.org/2.7/library/xml.dom.html#module-xml.dom>`_ å’Œ `xml.sax <https://docs.python.org/2.7/library/xml.sax.html#module-xml.sax>`_ 包为æµè¡Œçš„ä¿¡æ¯äº¤æ¢æ ¼å¼æä¾›äº†å¼ºå¤§çš„æ”¯æŒã€‚ åŒæ ·ï¼Œ`csv <https://docs.python.org/2.7/library/csv.html#module-csv>`_ æ¨¡å—æ”¯æŒåœ¨é€šç”¨æ•°æ®åº“æ ¼å¼ä¸ç›´æŽ¥è¯»å†™ã€‚综åˆèµ·æ¥ï¼Œè¿™äº›æ¨¡å—和包大大简化了 Python 应用程åºå’Œå…¶å®ƒå·¥å…·ä¹‹é—´çš„æ•°æ®äº¤æ¢ã€‚ * 国际化由 `gettext <https://docs.python.org/2.7/library/gettext.html#module-gettext>`_, `locale <https://docs.python.org/2.7/library/locale.html#module-locale>`_ å’Œ `codecs <https://docs.python.org/2.7/library/codecs.html#module-codecs>`_ 包支æŒã€‚