Python学习笔记-王纯业


Python ÆS)P X’ LeafWang@163bj.com or AnnCharles@tom.com 2003c0826F annCharles@tom.com 12,208 Python ÆS)P 8 ¹ 8 ¹ 111˜˜˜ÙÙÙ Python000 1 §1.1 m© ......................................... 2 §1.1.1 XÛ$1Python§S............................ 2 §1.2 ˜ƒé– .................................... 3 §1.3 Äa....................................... 3 §1.3.1 .(integer) ................................ 3 §1.3.2 2:.(float) ................................ 3 §1.3.3 Nonea................................... 3 §1.3.4 Ü6Lˆª ................................. 3 §1.4 L(list) ...................................... 6 §1.4.1 Mïlist ................................... 6 §1.4.2 listeIÚflist .............................. 6 §1.4.3 flistJ ................................. 7 §1.4.4 ?nlist{ ............................... 8 §1.4.5 ^list [Ù¦~^êâ( ....................... 10 §1.4.6 list comprehension ............................. 12 §1.5 iÎG(string) ................................... 13 §1.5.1 iÎGL«................................ 13 §1.5.2 =†¤Ù¦a.............................. 14 §1.5.3 iÎGöŠ ................................ 14 §1.6 |(tuple) ..................................... 22 §1.7 S(sequence) ................................... 23 §1.8 i;(dictionary) .................................. 23 §1.8.1 {ü~f .................................. 24 §1.8.2 dictionaryöŠ .............................. 24 §1.9 §S6§ ...................................... 27 §1.9.1 ©|(if .................................. 27 §1.9.2 ̂(for§while§break§continue§range() ............. 29 annCharles@tom.com 1i,208 Python ÆS)P 8 ¹ §1.10 ¼ê ........................................ 32 §1.10.1 ļê^{.............................. 32 §1.10.2 ëê‡êŒÀ§ëêk%@Š ...................... 33 §1.10.3 UC¼êëêDŠ^S.......................... 34 §1.10.4 ‡êŒCëê ............................... 34 §1.10.5 Doc String ¼ê£ã ........................... 36 §1.10.6 lambda¼ê ................................ 36 §1.10.7 ¼êŠ^(scope) ........................... 37 §1.10.8 i@¼ê(nested) ............................. 38 §1.10.9 functionëêD4 ............................ 38 §1.11 ¬(module)ڝ(package) ........................... 39 §1.11.1 Mmodule .............................. 39 §1.11.2 Noémodule .............................. 41 §1.11.3 package()................................ 42 §1.12 name space(·¶˜m).............................. 42 §1.13 a .......................................... 46 §1.13.1 Ÿo´object ................................ 46 §1.13.2 Ÿo´class oject ............................. 48 §1.13.3 property Úmethord ............................ 50 §1.13.4 bound methord Úunbound methord .................. 52 §1.13.5 U«(inherit) ................................ 54 §1.13.6 ·¤ Cþ ............................... 54 §1.13.7 Abstrace Class .............................. 55 §1.13.8 hkattribute ............................... 55 §1.13.9 Python ¥class AÏmethord ..................... 56 §1.13.10 ˜ AÏ­1¼ê^{Þ~ .................... 63 §1.13.11 new style class .............................. 75 §1.14 É~?n(exception) ............................... 82 §1.14.1 Ÿo´É~?n§Ÿo‡kÉ~?n ................. 82 §1.14.2 Ó¼exception(É~)........................... 84 §1.14.3 Ñexception ............................... 88 annCharles@tom.com 1ii,208 Python ÆS)P 8 ¹ 111ÙÙÙ mmmuuuPython ¦¦¦^^^óóóäää 91 §2.1 ¦^Emacs ?6Python §S........................... 91 §2.1.1 SCpython mode .............................. 91 §2.1.2 python mode ÄA5 ......................... 92 §2.1.3 ~^õUÞ~ ................................ 92 §2.2 Ù¦?6ì ..................................... 94 §2.3 NÁ§S...................................... 95 §2.3.1 ¦^DDD Úpydb NÁpython §S.................... 95 111nnnÙÙÙ Python ~~~^^^¬¬¬ 96 §3.1 S˜¬ ...................................... 96 §3.1.1 ~^¼ê .................................. 96 §3.1.2 a.=†¼ê ................................ 98 §3.1.3 ^u‰1§SS˜¼ê ......................... 100 §3.2 ÚöŠXڃ'N^ ............................... 103 §3.2.1 ‹m©‡ .................................. 106 §3.2.2 Ö©‡ .................................. 106 §3.2.3 '4©‡ .................................. 107 §3.3 regular expression ................................. 107 §3.3.1 {üregexp ................................ 108 §3.3.2 iÎ8Ü.................................. 108 §3.3.3 ­E..................................... 110 §3.3.4 ¦^©iÎG.............................. 110 §3.3.5 ¦^re ¬ ................................. 110 §3.3.6 p?regexp ................................. 112 §3.3.7 ©|(Group) ................................ 113 §3.3.8 Compile Flag ................................ 115 §3.4 ^struct¬?n?›êâ ........................... 116 §3.5 ^Cmd ¬?{ü·-1 ........................ 118 §3.5.1 {ü~f ................................. 119 §3.5.2 ½Â%@·-................................ 120 §3.5.3 ?nEOF .................................. 120 annCharles@tom.com 1iii,208 Python ÆS)P 8 ¹ §3.5.4 ?n˜·-................................. 121 §3.5.5 ·-1gÄÖà .............................. 121 §3.5.6 UCIOÑ\ÑÑ............................. 121 §3.5.7 UCJ«Î................................. 122 §3.5.8 Jø3‚ÏõU............................. 122 §3.5.9 $1Shell õU.............................. 123 §3.5.10 getattr õU¦^ ............................ 123 §3.6 ?n·-1À‘ .................................. 124 §3.6.1 ˜‡{ü~f .............................. 124 §3.6.2 ‘këê·-1À‘ ........................... 125 §3.6.3 optparser ¬ ............................... 126 §3.7 'užm¬ .................................. 136 §3.8 socket ?§ ..................................... 136 §3.8.1 0 ..................................... 136 §3.8.2 {ü~f ................................. 138 §3.8.3 Mïsocket ................................. 139 §3.8.4 ”½socket ................................. 140 §3.8.5 ïáë .................................. 141 §3.8.6 Âxêâ .................................. 141 §3.8.7 ämë .................................. 142 §3.8.8 Ù¦9ϼê ................................ 143 §3.8.9 TCP ÚUDP «O............................ 145 §3.8.10 'uTCP ÑÖì{K......................... 146 §3.9 Âe‡ ...................................... 150 §3.10 POP3 Æ0 .................................. 150 §3.10.1 ˜‡{ü~f .............................. 150 §3.10.2 ¦^POP3 ÆÂe‡ ......................... 151 §3.10.3 õ1A?n .............................. 151 §3.10.4 POP3Ï&L§¥G ......................... 152 §3.10.5 POP3¥·-.............................. 152 §3.11 ^poplib ¬Âe‡ .............................. 158 annCharles@tom.com 1iv,208 Python ÆS)P 8 ¹ §3.12 SMTP Æ0 .................................. 160 §3.12.1 SMTP˜‡~f ............................. 160 §3.12.2 uxe‡·-.............................. 162 §3.12.3 Ù¦·-.................................. 164 §3.12.4 ESMTP .................................. 166 §3.12.5 ¹@y .................................. 166 111oooÙÙÙ Tkinter ???§§§ 167 §4.1 Tkinter0 ..................................... 167 §4.1.1 Ÿo´Tkinter ............................... 167 §4.2 Hello Tkinter §S................................. 168 §4.2.1 {ü~f ................................. 168 §4.2.2 ,˜‡{ü§S.............................. 170 §4.3 Widget ˜ ................................... 171 §4.4 Geometry Manager(AÛ+nì)......................... 172 §4.4.1 Pack +nì ................................. 173 §4.4.2 Grid +nì ................................. 176 §4.5 Widget ª ................................... 178 §4.5.1 ôÚ..................................... 178 §4.5.2 iN..................................... 179 §4.5.3 ©i‚ªz ................................. 182 §4.5.4 >µ ..................................... 182 §4.5.5 àI..................................... 184 §4.6 ¯‡Ú¯‡½ ................................. 186 §4.6.1 ˜‡{ü~f .............................. 186 §4.6.2 ¯‡?n¼ê ................................ 188 §4.6.3 ¯‡g ................................. 188 §4.6.4 Ә‡¯‡õ‡?n¼ê ........................ 191 §4.6.5 ÚWM ƒ'¯‡”½ .......................... 192 §4.7 ~^A^§S¦^Widget ........................... 193 §4.7.1 ÄI .................................. 193 §4.7.2 èü ..................................... 193 annCharles@tom.com 1v,208 Python ÆS)P 8 ¹ §4.7.3 óä9 .................................... 197 §4.7.4 G9 .................................... 197 §4.7.5 IOé{µ ................................. 199 111ÊÊÊÙÙÙ Python***ÐÐÐ 205 §5.1 ^C?*Ь .................................. 205 annCharles@tom.com 1vi,208 Python ÆS)P  ã  ã 3-1 žm¼êƒm'X................................ 137 3-2 ràÚÑÖìà¼êN^6§ ........................ 139 4-1 Tkinter XÚgã ................................. 167 4-2 hello1.py $1(J................................ 169 4-3 hello2.py $1(J................................ 171 4-4 border1.py $1(J............................... 183 4-5 cursor1.py $1(J............................... 185 4-6 menubar2.py $1(J.............................. 194 4-7 menubar3.py $1(J.............................. 196 4-8 toolbar1.py $1(J.............................. 198 4-9 statusbar1.py $1(J............................. 199 4-10 inputpassword.py $1(J........................... 203 annCharles@tom.com 1vii,208 Python ÆS)P L ‚ L ‚ 1.5-1 iÎG¥=¿iÎ............................... 14 1.5-2 iÎG=†Ù¦a............................... 14 1.5-3 äiÎG´Äáu,«aO¼ê ...................... 16 1.13-4 Œ±­1ŽâöŠÎ¼ê ........................... 63 3.1-1 Python ­^S˜¼ê ............................. 97 3.1-2 a.=†¼ê ................................... 99 3.2-3 XÚN^Þ~ ................................... 103 3.4-4 struct ¬¥‚ª½Â............................. 117 3.4-5 i!^S½Â................................... 118 3.5-6 ·-1?6¯$… ............................... 119 3.7-7 L«žm ..................................... 137 3.8-8 ^u=†i!^S¼ê ............................. 145 3.8-9 TCP ÚUDP «O............................... 146 3.11-10 poplib ·-o(................................. 160 4.5-1 tkFont |±option ............................... 181 4.6-2 ¯‡£ãÞ~ ................................... 189 4.6-3 £ã¯‡ëê .................................. 189 annCharles@tom.com 1viii,208 Python ÆS)P 111˜˜˜ÙÙÙ Python000 python´˜«)º5¡•é–Šó"pythonk±eA:" )))ººº... „Ý ú§mu±Ïá§NÁN´§g·*Ð5"dukevalõU§? §SŒ±3$1žUYmu"ù´éõ)º.Šó5"XVB kScript Engi- neer§LispkEVAL§—EmacsrŒ*Ð5" ¡¡¡•••éé閖– 3Python¥§a(class)§¼ê(function)§¬(module) Ñ´é–"§Ü `§¦'Java§C++ \OO( Object Oriented)"O4·ò\“Ÿo‰OO? Java OO?”?Ø¥§^LÒ "z‡ŠóÑkˆg`":§ Python á  õŠó`:" ŒŒŒ***ÐÐÐ Python ¦^CŠó§ég,^C½öC++Šó*ÐPythonA5"X? #¬§O\#êâa." ŒŒŒiii\\\ Python)ºìڙŒ±éN´i\^rgCC½öC++Šó§S‘8 ¥§¦\§SŒ±|± ?§§*ÐõU"y3ÒkPython¬Œ±* ÐVIMÚEmacsõU" SSSØØØ PythonØ%)ºì´é" ÄÄÄaaa...ØI‡¯k(²(declare)Cþa.§†¦^CþҔéõÙ¦)º.Š óVB§VB Script§JScript§PERL˜" rrraaa... ¦+CþØ^(²(declare)a.§´˜Cþk Š§@où‡Š´k˜‡a. "ØUòstringa.Cþ†DŠ‰˜‡integera.Cþ§ ´I‡a.=†" ùÚVB§VBScript§JScript§PERLؘ§ÚJava ”" annCharles@tom.com 11,208 Python ÆS)P ˜ Python0 §1.1 m© §1.1.1 XÛ$1Python§S Python ´ ˜ «) º .  ? § Š ó § ÚÙ ¦ ) º .? § Š ó § XPerl§VB§Bash§Awk§Sed Ñkaq§$1{Xe" • 1˜«{´pª"b\´3Unix ‚¸e§$ ´·-1J«ÎÒ" $python Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World" Hello World >>> #U CTRL+D òÑ 3Windows ¥kaq‚¸"©¥Œõê~fÑ´3pª$1">>>Ú...L «Python J«ÎÒ"Bash eéõ·-1?6·-Ñ´Œ±¦^§XC-a §C-e §C-w §Ï¦‚Ñ´¦^readline ¥" • „Œ±r§S3˜‡©‡¥§^python )ºìN^" $cat test.py print "Hello World" $python test.py Hello World $cat test.py | python #+öŠ Hello World $python < test.py #Ñ\­½• Hello World • r§SŠ˜‡Œ±$1Unix ©‡" $cat test.py #!/usr/bin/python print "Hello World" $ls -l test.py -rw-r--r-- 1 chunywan mnw 40 Sep 12 13:34 test.py $chmod +x test.py $ls -l test.py annCharles@tom.com 12,208 Python ÆS)P §1.2 ˜ƒé– -rwxr-xr-x 1 chunywan mnw 40 Sep 12 13:34 test.py $./test.py Hello World 5¿1˜1AÏ5ºŠé§ù´Unix eÏ^{"Perl§Tl/Tcl§Sed§awk§Bash Ñ´ùo^" Š5¿´5ºŠé§#¡L«5º"Úbash˜"5ºŠé3NÁ§Sžÿ§ ´ék^§„Œ±Jp§SŒÖ5" §1.2 ˜ƒé– a(class)§¼ê(function)§¬(module) Ñ´é–"“˜ƒÑ´é–§é–Ñk¶ i”§ù´·˜‡o(" §1.3 Äa. §1.3.1 .(integer) wå5”êLˆªÒ´."k±e$Ž öŠÎ¿Â ~f (J + \{ 1+1 2 − ~{ 1-1 0 ∗ ¦{ 2*10 20 /Ø{ 10/3 3 %  10/3 1 ∗∗ ˜ 2**4 16 divmod Ø{ divmod(10§3) (3§1) §1.3.2 2:.(float) wå5”2:êLˆªÒ´2:ê"Ú.aq"5¿§1´.§1.0´2:."Ü 6Lˆª1 == 1.0 ´ýŠ"5¿§2:ê$Ž´kØ "^u‰ÆOŽžÿ§I‡ Ù¦¬|±"ù´Ï2:$ŽìUL«k ê" §1.3.3 Nonea. None´˜‡AÏ~þ§L«Ñ†"3±Œ±w¦^?" §1.3.4 Ü6Lˆª Python¥vkbooleana."ҔCŠó¥§Ø 0± §Ù¦Ñ´ý"´Python¥ “b”kéõ§) annCharles@tom.com 13,208 Python ÆS)P ˜ Python0 None,0,0.0,"" (˜iÎG),[](˜list),()(˜tuple),{}(˜dictionary) Python¥k±eÜ6$ŽÎ" and Ü6† or Ü6½ not Ü6‡ >>> def getTrue(): ... print "debug: true" ... return 1 ... >>> def getFalse(): ... print "debug: false" ... return 0 ... >>> if getTrue() and getFalse(): ... print "ok" ... else: ... print "bad" ... debug: true # k$1 getTrue debug: false # XJ getTrue ˆ£ý,@o$1getFalse bad # ‡(J´ getFalse ˆ£(J. >>> if getFalse() and getTrue(): ... print "ok" ... else: ... print "bad" ... debug: false #k$1 getFalse bad #XJ getFalse ˆ£b,@oÒØ$1 getTrue >>> Š5¿´and Úor §éuand 5`§~Xexpr1 and expr2§XJexpr1 ´Ü6b§@ oÒoLˆª†ˆ£expr1 §N´˜iÎG§½ö˜list§ Ø2OŽexpr2§Ò´ `expr2 ¥XJk¼êN^{§Ø¬‰1"XJexpr1 ´Ü6ý§@oâ¬OŽexpr2 §‡Ü6LˆªÒˆ£expr2"éuor 5`§~Xexpr1 or expr2§XJexpr1 ´Ü6 ý§@oÒoLˆª†ˆ£expr1 § Ø2OŽexpr2§Ò´`expr2 ¥XJk¼ê N^{§Ø¬‰1"XJexpr1 ´Ü6b§@oâ¬OŽexpr2 §‡Ü6LˆªÒˆ £expr2"ùÒk˜«~^AÏLˆª: annCharles@tom.com 14,208 Python ÆS)P §1.3 Äa. and or ¦k˜‡ék^ŠÂ´:XJcond ¤á§@oˆ£expr_true§ÄKˆ£expr_false" ¦vkŠ‡Ÿo5K§´l†mg"4·‚5u˜eŸo: cond expr_true expr_false o(J ý ý ?Û(ØOŽ) expr_true b ?Û(ØOŽ) ý expr_false b ?Û(ØOŽ) b expr_false ý b b expr_false ý b ý expr_false lù‡LþŒ±w: • ޘ|`² §XJcond ´ý§@o‡LˆªÒ´expr_true • 1|`² §XJcond ´b§@o‡LˆªÒ´expr_false • ˜|`² §·`œ "P4XJexpr_true kŒU´bžÿ§Ø‡ùo‰§ ϏkŒU‹»5ŠÂ§cond ´ýžÿ§‡Lˆª%´expr_false")û ù‡¯K{Ò´: ( and (,) or (,))[0]  ¡)Òr‡Lˆª)å5§UCOŽ`k?§ÄK[0] `k?p"¥m )ÒÚÏÒ§´˜‡tuple Lˆª"ù(,)[´ý§Ï¦´¹ k˜‡ƒtuple§[0] L«JÑù‡ƒ5"3$´§Ï~ù‡Lˆ ª´^3'{üœ¹e§{üDŠŠé§expr_trueÚexpr_false ˜„Ñ´~ þ§ …´ý" >>> x= cond and "OK" or "BAD" >>> x ’OK’ >>> cond = 0 >>> x= cond and "OK" or "BAD" >>> x ’BAD’ >>> Ón: or and kaqŠÂ§´Ø‡¦^ù«Lˆª§Ø´Ïù‡LˆªØÜ{§ ´Ï ¦ØÎÜS."?§ŠóÚg,Šókaq/§Ò–·‚²ž¬`§“r§¯Œ”§ annCharles@tom.com 15,208 Python ÆS)P ˜ Python0 ´·‚ج`§“r§?ꔧ½ö“r§?  ”§Ø´Ï@o`Ò´†§´ÏØ ÜS."@Ò¬¯§ŸoØÜS.§S.l=p5ºÏ´lC Šó¥5"C Šó¥k cond ? true_expr: false_expr ù´˜‡nöŠÎ§¯õC Šó¦^ö^ A›c §Ú1˜«ŠÂ´aq" oƒ§# ¡@«ª§1˜«ÒÐ " §1.4 L(list) list aquC++¥vector§C Šó¥ê|§^u;^S("X§ ˜c¥z‡U꧌±L« [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] ˜c¥z‡¶¡§Œ±L« [ ’January’, ’February’, ’March’, ’April’, ’May’, ’June’, ’July’, ’August’, ’September’, ’October’, ’November’, ’December’ ] z‡(϶i§Œ±L« [ ’Monday’,’Tuesday’, ’Wednesday’, ’Thursday’ , ’Friday’, ’Saturday’, ’Sunday’] §1.4.1 Mïlist a=[’1’,’2’] ^[])å5§L«˜‡list§¥mˆ‡ƒŒ±´?Ûa.§^ÏÒ©…" §1.4.2 listeIÚflist listeIl0m©§ÚCŠóaq§´O\ KeI¦^" -len 1˜‡ƒ ... ... -2 ê1‡ƒ -1 ˜‡ƒ 0 1˜‡ƒ 1 1‡ƒ ... ... len-1 ˜‡ƒ >>> a=[0,1,2,3,4,5,6] annCharles@tom.com 16,208 Python ÆS)P §1.4 L(list) >>> i=-len(a) >>> while i < len(a): ... print "a[",i,"]=",a[i] ... i=i+1 ... a[ -7 ]= 0 a[ -6 ]= 1 a[ -5 ]= 2 a[ -4 ]= 3 a[ -3 ]= 4 a[ -2 ]= 5 a[ -1 ]= 6 a[ 0 ]= 0 a[ 1 ]= 1 a[ 2 ]= 2 a[ 3 ]= 3 a[ 4 ]= 4 a[ 5 ]= 5 a[ 6 ]= 6 5¿whileŠé ?"¬3¡0 "a[-8] Úa[9] ѬÚå." >>> a[-8] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range >>> a[7] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range §1.4.3 flistJ ŒÏLeI½‰Œ§^uJј‡list˜Ü©"eIL² ˜§˜‡å© ˜§ ˜‡(堘§¥m^kÒ©…"XJ؍½å© ˜§å© ˜´0 §XJ؍½(å  ˜§(堘´ −1"flist L«)å© ˜?ƒ§˜—(堘§´Ø)(å  ˜ƒ" KeIŒ±ë†½Âå© ˜§½ö(堘" >>> a[1:4] annCharles@tom.com 17,208 Python ÆS)P ˜ Python0 [1, 2, 3] >>> a[:] [0, 1, 2, 3, 4, 5, 6] >>> a[1:] [1, 2, 3, 4, 5, 6] >>> a[:3] [0, 1, 2] >>> a[:] [0, 1, 2, 3, 4, 5, 6] >>> a[1:-1] [1, 2, 3, 4, 5] flist ´5list ˜‡€§˜‡B§UCflist جUC5list" §1.4.4 ?nlist{ • L.append(var) §J\ƒ" >>> a=[0,1,2,3,4,5] >>> a.append(6) >>> a [0, 1, 2, 3, 4, 5, 6] >>> • L.count(var) OŽvar 3L¥Ñygê" >>> a=[0,2,2,2,3,3] >>> a.count(2) 3 >>> a.count(3) 2 • len(L) ˆ£L Ý" >>> a=[1,2,3] >>> len(a) 3 • L.extend(list) §òlistJ\3L¡" >>> a=[1,2,3] >>> a.extend([4,5,6]) annCharles@tom.com 18,208 Python ÆS)P §1.4 L(list) >>> a [1, 2, 3, 4, 5, 6] • L.index(var) ˆ£var3L¥ ˜§eçKÑÉ~" >>> a=[1,2,3,4,4,5] >>> a.index(4) 3 >>> a.index(6) Traceback (most recent call last): File "", line 1, in ? ValueError: list.index(x): x not in list • L.insert(index,var) 3index?§\var§Ù{ƒ•í"XJindexŒulist ݧÒ3V\"XJindexu0§Ò3m©?V\" >>> a=[1,2] >>> a.insert(0,1) >>> a [1, 1, 2] >>> a.insert(100,100) >>> a [1, 1, 2, 100] >>> a.insert(2,3) >>> a [1, 1, 3, 2, 100] • L.pop() ˆ£˜‡ƒ§¿…í؁˜‡ƒ"L.pop(index) ˆ£index? ƒ§¿…íØTƒ" >>> a=[0,1,2,3,] >>> a.pop() 3 >>> a.pop(0) 0 >>> a [1, 2] >>> • L.remove(var) évar§¿…í؃§eçÑÉ~" annCharles@tom.com 19,208 Python ÆS)P ˜ Python0 >>> a=["a","b","a","c","a","d"] >>> a.remove("a") >>> a [’b’, ’a’, ’c’, ’a’, ’d’] >>> a.remove("a") >>> a [’b’, ’c’, ’a’, ’d’] • L.reverse() òLS" >>> a=[1,2,3,4,5] >>> a.reverse() >>> a [5, 4, 3, 2, 1] • L.sort() §òaüS§a¥ƒea.ØÓ§(JgCw˜wj"˜„جùo‰"Q ,\ÑØ(½list¥ƒa.´Ä˜§\„‡üS§@o\ϖ´Ÿo(J? >>> a.sort() >>> a [1, 2, 3, 4, 5] >>> a=[1,"abc",2,"xxx"] >>> a.sort() >>> a [1, 2, ’abc’, ’xxx’] L.sort(func) §ò^funcŠ'¼ê§òüS"func(x,y)§ˆ£ −1§0§1©OL «u§u§Œu" §1.4.5 ^list [Ù¦~^êâ( ^list[æÒstack >>> a=[] >>> a.append(0) #ØÒ >>> a.append(1) >>> a.append(2) >>> a [0, 1, 2] >>> a.pop() #ÑÒ 2 annCharles@tom.com 110,208 Python ÆS)P §1.4 L(list) >>> a.pop() 1 >>> a.pop() 0 >>> ^list[èqueue >>> a.insert(-1,0) #\è >>> a.insert(-1,1) >>> a.insert(-1,2) >>> a [2, 1, 0] >>> a.pop() #Ñè 0 >>> a.pop() 1 >>> a.pop() 2 >>> a [] ½ö >>> a.append(0) >>> a.append(1) >>> a.append(2) >>> a.append(3) >>> a [0, 1, 2, 3] >>> a.pop(0) 0 >>> a.pop(0) 1 >>> a.pop(0) 2 >>> a.pop(0) 3 annCharles@tom.com 111,208 Python ÆS)P ˜ Python0 ^list[ätree >>> leaf1=[0,1] >>> leaf2=[2,3] >>> leaf3=[4,5] >>> leaf4=[6,7] >>> branch1=[leaf1,leaf2] >>> branch2=[leaf3,leaf4] >>> root=[branch1,branch2] >>> root [[[0, 1], [2, 3]], [[4, 5], [6, 7]]] §1.4.6 list comprehension Š{: [ for k in L if ] ŠÂ: returnList=[] for k in L: if : returnList.append() return returnList; ˆ£˜‡list§listƒdz˜‡expr1 |¤§if Šé^uLȧŒkŒÃ" >>> a=["123","456","abc","Abc","AAA"] >>> [ k.center(9) for k in a ] [’ 123 ’, ’ 456 ’, ’ abc ’, ’ Abc ’, ’ AAA ’] #a¥=di1|¤iÎG§¿r¦C¤Œ" >>> [ k.upper() for k in a if k.isalpha() ] [’ABC’, ’ABC’, ’AAA’] #a¥=dŒi1|¤iÎG§¿r¦C¤" >>> [ k.lower() for k in a if k.isupper() ] [’aaa’] #a¥=kêi¤iÎG§¿r¦C¤êa." >>> [ int(k) for k in a if k.isdigit() ] [123, 456] LÈ(filter)§ÚN(mapping)ڏ˜" ¦+ù‡^{é{ü§´%›©k^§§SC{'§ŒÖ5r"kéõžÿ§·‚ ¦^̂Šé§==‰é{ü¯œ§´Ì‚Šé´éØÐ֧Ϗ̂ŠéØÎ annCharles@tom.com 112,208 Python ÆS)P §1.5 iÎG(string) Üg,Šó¥S."~Xµþ¡~f¥§k˜‡L«“rlist ¥z‡iÎG¥iÎ C¤Œ”"´XJ^̂ŠéL«Ò´:“M˜list§éulist ¥z˜‡ƒ§r ù‡iÎGC¤Œ§V\#ïlist¥"” „kéõ~f§4·‚ég,A^ù«^{" rlist¥¤kƒ\ 1 [ k+1 for k in list] JÑ list ¥¤kêCþ [ k for k in list if type(k)==types.IntType] r list ¥¤kêƒO\˜ [ k + 1 for k in list if type(k)==types.IntType ] ·š~Uù«Lˆªœ §1.5 iÎG(string) §1.5.1 iÎGL« ^üÚÒ½VÚÒ¤iÎG ’hello’ "world" k˜ iδÃ{^…Ñ\§¤±^iÎ|ÜL«AÏiÎ"XL1.5-1" ù´ÚC Šó›©aq§„kecho ·-§Java ŠóÑ´ùoL«˜‡AÏiÎ" XJ‡Ñ\˜‡›©iÎG§˜1ؐB§Ò^ü1"ü‡iÎG¥md˜xiÎ ë§L«˜‡iÎG"X "abc" \ ’def’ L«“abcdef”§5¿Ú"abc"+"def"´k«O§‘+L«ü‡iÎGë˜å§^˜ xiÎë§L«˜‡iÎG" XJ‡Ñ\˜‡›©›©iÎG§Ò^n‡ëYVÚÒG"X """ this is a very very long string. And it contains a lot line. it is suitable to write document of function. """ annCharles@tom.com 113,208 Python ÆS)P ˜ Python0 “è L«iο 5 \newline à Ñ ^ uëõ‡á 1§¤˜‡ 1 \\ \ ‡m \’ ’ üÚÒ \" "VÚÒ \a 0x07 $ ASCII ››iÎ \b 0x08 ò‚ ASCII ››iÎ \f 0x0c Formfeed (FF) ASCII ››iÎ \n 0x0a †1 ASCII ››iÎ \N{name} Unicode iÎ éuUnicode \r 0x0d £ ASCII ››iÎ \t 0x09 Y²›LÎ \v 0x0b R†›LÎ \u{xxxx} Unicode?è éuUnicode \ooo 0xooo ooo L«l?›iÎ \xhh 0xhh hh L«›8?›iÎ L 1.5-1: iÎG¥=¿iÎ ¼ê¶¡ õU ~f (J float(str) C¤2:ê float("1e-1") 0.1 int(str) C¤. int("12") 12 int(str,base) C¤base?›ê int("11",2) 2 long(str) C¤. int("12") 12 long(str,base) C¤base?›ê int("11",2) 2 L 1.5-2: iÎG=†Ù¦a. §1.5.2 =†¤Ù¦a. §1.5.3 iÎGöŠ éü‡iÎG >>> "Hello" + " " + "World" ’Hello World’ Œ=† >>> "this is test".capitalize() #Äi1Œ annCharles@tom.com 114,208 Python ÆS)P §1.5 iÎG(string) ’This is test’ >>> "THIS IS TEST".capitalize() ’This is test’ >>> "THIS IS TEST".lower() #ÜC¤ ’this is test’ >>> "this is test".upper() #ÜC¤Œ ’THIS IS TEST’ >>> "This Is Test".swapcase() #Œp† ’tHIS iS tEST’ iÎGÝ >>> len("Hello World") 11 iÎGfG Œ±r˜‡iÎGw¤˜‡¹kéõiÎlist§ùŒ±^ÚlistƒÓªf G"eIl0m©"Kê“L‡•" >>> str="Hello World" >>> str="Hello" >>> i=-len(str) >>> while i < len(str): ... print "str[",i,"]=",str[i] ... i=i+1 ... str[ -5 ]= H str[ -4 ]= e str[ -3 ]= l str[ -2 ]= l str[ -1 ]= o str[ 0 ]= H str[ 1 ]= e str[ 2 ]= l str[ 3 ]= l str[ 4 ]= o >>> kҌ±L«‰Œ§fiÎG"kÒü>êL«e.Úþ.§e.Úþ.Ñ´ŒÀ§ "Žþ3-1§e.0" annCharles@tom.com 115,208 Python ÆS)P ˜ Python0 >>> str="Hello" >>> str[:] ’Hello’ >>> str[1:2] ’e’ >>> str[1:-1] ’ell’ >>> str[-1:2] ’’ Ke.´“L ˜§Ø“LŒ"¤±lù‡¿Âþù§−1 ‡'2 Œ"str[-1:2]´˜ iÎG"AT5¿¦fiÎG´ý5iÎG€§UCiÎG´Ø¬UC 5iÎG"،±^fiÎGªUC5iÎG"X: >>> a="abcd" >>> b=a[1:2] >>> b="x" #UC b >>> a ’abcd’ #جK a >>> a[1]=’abc’ # Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn’t support item assignment >>> äiÎG´Äáu,«aO L1.5-3¥{Œ±äiÎG¥´ÄÎÜ, ^‡"iÎG÷v^‡§Òˆ£1§Ä K§ˆ£0" ¶¡ ^‡ s.isalnum() ¤kiÎÑ´êi0123456789 ½öi1A-Z§a-z s.isalpha() ¤kiÎÑ´i1a-z ½öA-Z s.isdigit() ¤kiÎÑ´êi0123456789 s.islower() ¤kiÎÑ´i1a-z s.isupper() ¤kiÎÑ´Œi1A-Z s.istitle() ¤kücÑ´Äi1Œ§”‡title s.isspace() ¤kiÎÑ´˜xiÎ\n,\t,\r,’ ’ L 1.5-3: äiÎG´Äáu,«aO¼ê annCharles@tom.com 116,208 Python ÆS)P §1.5 iÎG(string) 3iÎG¥éfG • s.find(substring,[start [,end]]) XJ駈£¢ÚŠ§L²´3=ké "XJéاˆ£ −1 #ok¡abc§a mÞ ˜ 3, >>> "ok abc abc abc".find("abc") 3 #l ˜4±m©é"ƒu s[4:].find("abc") >>> "ok abc abc abc".find("abc",4) 7 #ƒu s[4:9].find("abc") >>> "ok abc abc abc".find("abc",4,9) -1 #ƒu s[4:10].find("abc") >>> "ok abc abc abc".find("abc",4,10) 7 • s.rfind(substring,[start [,end]]) Úfind()aq§´´‡•é" >>> "ok abc abc abc".rfind("abc") 11 • s.index(substring,[start [,end]] Úfind()aq§´XJéØsubstring§Ò )˜‡ValueErrorÉ~"ü«ªØÓ3u†Ø?nØÓ" >>> "ok abc abc abc".index("abc") 3 >>> "ok abc abc abc".index("abcd") Traceback (most recent call last): File "", line 1, in ? ValueError: substring not found in string.index • s.rindex(substring,[start [,end]] Ús.index()aq"ØӃ?3u´‡•é" • s.count(substring,[start [,end]]) ˆ£ésubstringgê" >>> "ok abc abc abc".count("abc") 3 annCharles@tom.com 117,208 Python ÆS)P ˜ Python0 ‚ªziÎG Ä  ^ { ´ s % §tuple L« ˜ ‡ ë ê  L § a q uCŠ ó ¥printf§ rtuple ¥z˜‡Š^iÎGL«§L«‚ªds 5(½" >>> print "%s’s height is %dcm"%("Charles",180) Charles’s height is 180cm 5¿%s,%dÚCŠó¥printf´aq§âŠ‰conversion specifier§(=†½Â) y3X­?Øconversion specifier"conversion specifier k±eA‡Ü©¤§ %[][][]| [][]| wXéE,§Ù¢‡˜‡%˜‡conversion typeҌ± "٦ѴŒÀ "conversion typeXe: • d L«kÎқ?›ê" >>> "%d and %d" % (-1,2) -1 and 2 • i Ód • o L«ÃÎÒl?›ê" >>> "%o and %o" % (16,8) 20 and 10 • u L«ÃÎÒê" >>> "%u and %u" %(-10,10) ’4294967286 and 10’ 5¿ −10 )º¤ÃÎÒêžÿ§L«˜‡éŒê"ù´Ï3OŽÅ¥^ ÖèL«Kê§Kêp ´1§3)º¤ÃÎÒêžÿ§Ò¬éŒ" • x L«ÃÎқ8?›() >>> "%x and %x" % (100,200) ’64 and c8’ •XL«ÃÎқ8?›(Œ) >>> "%X and %X" % (100,200) ’64 and C8’ annCharles@tom.com 118,208 Python ÆS)P §1.5 iÎG(string) • e 2:꧉ÆLˆª{() >>> "%e and %e"%(-100,200) 2.000000e+02 •E 2:꧉ÆLˆª{(Œ) >>> "%E and %E"%(-100,200) 2.000000E+02 • f L«2:ê >>> "%f and %f"%(-0.00001,200.0) ’-0.000010 and 200.000000’ • g L«2:ê§XJ´u0.0001½öØ °Ý§Ò^‰ÆL«{" >>> "%g and %g"%(-0.00001,2000000.0) ’-1e-05 and 2e+06’ • c rASCII êL«ü‡iÎ >>> "%c and %c"%(67,68) ’C and D’ Œ^uCêASCIIiÎ • r L«˜‡iÎG§ù‡iÎG¦^repr()ˆ£Š >>> "%r"%({"one":1,"two":2}) "{’two’: 2, ’one’: 1}" Úprint expr(obj) ‹<Ñ5J˜" • s L«˜‡iÎG§ù‡iÎG¦^str()¼êˆ£Š >>> "%s"%({"one":1,"two":2}) "{’two’: 2, ’one’: 1}" Úprint str(obj) ‹<Ñ5J˜" 5¿str Úexpr ¼êØÓ"str ´˜‡é–šª£ã"expr ´˜ ‡iÎG§´˜‡Ü{Python LˆªŠé§Œ±é–" mapping key Š ^ ´ ^dictionary “ Otuple § ^mapping keyŠ keyL «dictionary¥ C þ " ù  ‘ 5  Ð? ´ § J p § S  Œ Ö 5 §%dÚ%(height)' §öŒÖ5‡Ð" …§Ó˜‡CþÑyüg±þ§3tuple¥Ò‡üg§ …‡5¿tuple¥ƒ^Sڇê؇†§^mapping keyªÒÐõ " annCharles@tom.com 119,208 Python ÆS)P ˜ Python0 >>> print "%s’s height is %d cm, %s’s weight is %d kg" % \ ... ("Charles",170,"Charles",70) Charles’s height is 170 cm, Charles’s weight is 70 kg >>> print "%(name)s’s height is %(height)d cm" \ ... ",%(name)s’s weight is %(weight)d kg" % \ ... {"name":"Charles","height":170,"weight":70} Charles’s height is 170 cm,Charles’s weight is 70 kg nameÑyüg§3mapping key¥§ÒØ^üg§ …ëê^SŒ±‘B" Úlocals()¼êƒܧ¬kÐJ§locals()ˆ£local name space (ÛÜ·¶˜ m) §´˜‡dictionary§Ù¥key´Cþ¶¡§value´CþŠ"globals()ˆ£global name space (Û·¶˜m) ùpÞ‡~f"3¡name space(·¶˜m)k[0 " >>> def fun(a,b): ... print "a is %(a)d,b is %(b)d" %locals() ... >>> fun(1,2) a is 1,b is 2 minimum field width L«Ý" >>> print "%10d,%10d"%(1,2) 1, 2 precision^5L«°Ý§é2:êkŠ^§‘koÊ\õU" >>> print "%10.2f,%10.2f"%(10.123456,20.126456) 10.12, 20.13 conversion flag ´é, a.åŠ^"#L«^alternate form§XJ´8?›§@oÒ3 c¡\0§XJ´›8?›Ò3c¡\0x ½ö0X éÙ¦a.ØåŠ^" >>> print "%#x,%#X,%#o" %(16,16,16) 0x10,0X10,020 0 L«^0Ö§¦ƒ÷vminimum field width" >>> print "%010d,%010d"%(1,2) 0000000001,0000000002 -L«†éà§XJÚ0Ӟ¦^@o0ÒØåŠ^" >>> print "%-010d,%-010d"%(1,2) 1 ,2 §˜‡˜‚§L«0Úêc¡\‡˜‚§Kêc¡\-§ annCharles@tom.com 120,208 Python ÆS)P §1.5 iÎG(string) >>> print "% 10d,% 10d,% 10d"%(-1,2,-0) -1, 2, 0 + L«w«ÎÒ§êw«+§Kêw«- >>> print "%+10d,%+10d,%+10d"%(-1,2,0) -1, +2, +0 lenght modifier Ñ" Ù¦{ü‚ªzõU • s.ljust(width) †éàXJsÝvkwidth@o§Ò3¡Ö˜‚§˜‡ ݏwidthiÎG"ÄKiÎGs" >>> "Hello World".ljust(1) ’Hello World’ >>> "Hello World".ljust(12) ’Hello World ’ >>> "Hello World".ljust(16) ’Hello World ’ • s.rjust(width) méàچéàaq" >>> "Hello World".rjust(16) ’ Hello World’ >>> "Hello World".rjust(1) ’Hello World’ • s.center(width) Ø¥aq§3üÞ֘‚§¦sݏwidth§XJsÝ 'widthŒ§@oŸoØ‰" >>> "Hello World".center(1) ’Hello World’ >>> "Hello World".center(16) ’ Hello World ’ • K˜xiÎs.lstrip() K†>˜xiÎs.rstrip() Km>˜xi Îs.lstrip() Kü>˜xiÎ >>> "\t a \t".lstrip() ’a ’ >>> "\t a \t".rstrip() annCharles@tom.com 121,208 Python ÆS)P ˜ Python0 ’ a’ >>> "\t a \t".strip() ’a’ #‡python 2.2.3¥O\ ˜‡ŒÀëêchars§L«íØÑy3chars¥iÎ"Î ‡s.strip ƒus.strip("\t \n\r")" iÎGÜ¿(join)Ú©)(split) s.join(words)§words´˜‡¹kiÎGtuple ½ölist "join^sŠ©…Î òwords¥iÎGëå5§Ü¿˜‡iÎG" >>> "\n".join(["Hello","World","Python","Said"]) ’Hello\nWorld\nPython\nSaid’ >>> print "\n".join(["Hello","World","Python","Said"]) Hello World Python Said s.split(words)§words´˜‡iÎG§L«©…Î"splitöŠÚjoinƒ‡"ò^s© )¤˜‡list" >>> "This is a book".split(" ") [’This’, ’is’, ’a’, ’book’] §1.6 |(tuple) P4±e5K§ÄþҌ±Ýºtuple" • tuple´~þlist"tupleØUpop§remove§insert{" • tuple ^() L«§Xa=(0§1§2§3§4)§)Ҍ±ŽÑ" • tuple Œ±^eIˆ£ƒ½öftuple" • tuple Œ±^uõ‡CþDŠ" >>> a,b=(1,2) >>> print a,b 1 2 >>> t=(1,2) >>> a,b=t >>> print a,b 1 2 annCharles@tom.com 122,208 Python ÆS)P §1.7 S(sequence) >>> a,b=b,a+1 >>> print a,b >>> 2,2 • L«¹k˜‡ƒtuple{´: (1§) ¡k‡ÏÒ§^5ÚüÕCþƒ« ©" tuple 'list 5UЧÒ´`§Ø^JøÄS+nõU" §1.7 S(sequence) sequence )string§list§tuple"¦‚Ñk±e˜ Ï^öŠ" • in ä,‡object ´Ø´3˜‡sequence ¥" >>> x=12 >>> l=[12,13] >>> if x in l : print "x is in l" ... x is in l >>> str="abcd" >>> if "a" in str: print " ok " ... ok >>> if 2 in T : print "OK" ... OK • sequenceÝlen(seq) • ÏLeIÙ¥˜‡ƒ" seq[i] • ÏL‘kÒeIfsequence§seq[start:end] • ^+ L«ëü‡sequence • ^*L«­E˜‡sequence§"a"*3 L«aaa§(1,2)*3L«(1,2,1,2,1,2) • Œ±¦^list comprehension" §1.8 i;(dictionary) dictionary ´ ˜ ‡ ÃS  ; (  " z ˜  ƒ ´ ˜ ‡pair§  )keyÚvalueü ‡ Ü © "key a . ´integer½ östring1"value a . ‘ B Ÿ o Ñ Œ ± "dictionary¥ v k ­E key"dictionary¥  z ˜ ‡  ƒ ´ ˜ ‡tuple§tuple¥ k ü ‡  ƒ § ù ‡tuplepair§pair¥c¡´key§¡value"Œ±^D[key] ªvalue" 1½ö?ÛӞ¹k hash Ú cmp {é– annCharles@tom.com 123,208 Python ÆS)P ˜ Python0 §1.8.1 {ü~f #M{ü dictionary ¦^ {} s)Ò)å5§ # z‡pair^ÏÒ©…§pair¥key3c§value3§kÒ©…" >>> pricelist={"clock":12,"table":100,"xiao":100 } #Ú^ dictionary ¥˜‡ƒ valuež§^ key ‰eI" >>> pricelist["clock"] 12 >>> del pricelist["clock"] >>> pricelist {’table’: 100, ’xiao’: 100} # dict(L) Œ±E˜‡ dictionary #Ù¥ L ´˜‡ list§ L¥z˜‡ƒ´˜‡tuple§ # tuple¥kü‡ƒ§c¡´key§¡value" >>> pricelist=dict([(’clock’,12),("table",100),("xiao",100)]) >>> pricelist {’table’: 100, ’xiao’: 100, ’clock’: 12} >>> pricelist=dict([(x,10*x) for x in [1,2,3]]) >>> pricelist {1: 10, 2: 20, 3: 30} #e阇Ø3key‰DŠöŠ§KO\˜‡pair" >>> pricelist["apple"]=12 #O\˜‡ ƒ >>> pricelist {’table’: 100, ’apple’: 12, ’xiao’: 100, ’clock’: 12} #XJÖØ3key§¬ÑÉ~" >>> pricelist["appled"] Traceback (most recent call last): File "", line 1, in ? KeyError: appled §1.8.2 dictionaryöŠ b a={"one":1,"two":2,"three":3,"four":4} ˜˜dictionary ¼ê¶¡D.clear() >>> a.clear() >>> a {} annCharles@tom.com 124,208 Python ÆS)P §1.8 i;(dictionary) ˜˜˜‡dictionary D.copy() ˜‡dictionary ˜‡€ >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> b=a.copy() >>> b {’four’: 4, ’one’: 1, ’three’: 3, ’two’: 2} >>> b["four"]=5 >>> b {’four’: 5, ’one’: 1, ’three’: 3, ’two’: 2} >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> c=a >>> c["four"]=5 >>> a {’four’: 5, ’three’: 3, ’two’: 2, ’one’: 1} >>> c {’four’: 5, ’three’: 3, ’two’: 2, ’one’: 1} €"lþ¡~fŒ±w§XJ†DŠc=a§@ocÚa˜§?UcSNÓ¬ Ka"´XJb=a.copy()§@ob´Õá§UbجKa" D.get(key) eD¥kkey§@oˆ£D[key]§ÄKˆ£None >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> print a.get("abc") None >>> print a.get("four") 4 >>> print a.get("abc",100) 100 D.get(key,default) ÚD.get(key)ØÓ3u§eÃkey§Kˆ£default§ Ø´None "D.get(key)ƒuD.get(key,None)" annCharles@tom.com 125,208 Python ÆS)P ˜ Python0 D.haskey(key) ^uäD ¥´Ä¹kkey§ƒukey in D.keys()" >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> print a.has_key("one") 1 >>> print a.has_key("abc") 0 D.items() ˜‡list§Ù¥z‡ƒ´˜‡¹kü‡ƒtuple(pair)§tuple¥c¡´key§ ¡´value >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> a.items() [(’four’, 4), (’three’, 3), (’two’, 2), (’one’, 1)] D.copy()ƒudict(D.items()) §´e–B§^copy()¯" D.keys() list§¹kD¥¤kkey" >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> a.keys() [’four’, ’three’, ’two’, ’one’] a.copy()„Œ±¤dict([(k,a[k]) for k in a.keys() ]) >>> dict([ (k,a[k]) for k in a.keys()]) {’four’: 4, ’one’: 1, ’three’: 3, ’two’: 2} ,§XJ==´ copy§Ø‡ùoZ§^a.copy()§Ï¯" D.values() list§¹kD¥¤kvalue" >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> a.values() [4, 3, 2, 1] annCharles@tom.com 126,208 Python ÆS)P §1.9 §S6§ D.update(E) lE¥#êâ"¿g´ for k in E.keys(): D[k]=E[k] ~Xµ >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> b={"five":5,"three":30} >>> b {’five’: 5, ’three’: 30} >>> b.update(a) >>> b {’four’: 4, ’five’: 5, ’one’: 1, ’three’: 3, ’two’: 2} ù«{Œ±^5l˜‡dictionary •,˜‡dictionary DŠ" D.popitem() ˜‡pair§¿…íئ"eD´˜§ÑÉ~" >>> print a.popitem() (’four’, 4) >>> print a.popitem() (’three’, 3) >>> print a.popitem() (’two’, 2) >>> print a.popitem() (’one’, 1) >>> print a.popitem() Traceback (most recent call last): File "", line 1, in ? KeyError: popitem(): dictionary is empty §1.9 §S6§ ?§Šó§S6§kn«§^S§©|§Ì‚" §1.9.1 ©|(if Š{ annCharles@tom.com 127,208 Python ÆS)P ˜ Python0 if : ½ö if : ½ö if else: ½ö if : elif : elif : ... else: ùpAT5¿±eA: • if ¡LˆªŒ±´?ÛLˆª§Ø None§0§""(˜iÎG)§[] (˜list)§{}( ˜dictionary ) ()(˜tuple )± §Ù¦Ñ´ý" • Lˆª±kÒ©…" • e´˜1{üLˆª§Œ±†‹3¡" • e´õ1Lˆª§Ò‡^ ?ª§L«˜|Šé"3Python¥vkPascal ¥ begin ... end §½öC Šó¥{} 5L«˜|Šém©Ú(å"Python@ Ó ?ÝŠé´˜|"ù´˜‡;ö„;¯œ"Ð?Ò´§Jp ŒÖ5§ ?Û>> if x>0: 2‡<@XJkswitch Šé¬Ð annCharles@tom.com 128,208 Python ÆS)P §1.9 §S6§ ... print "x is positive" ... elif x==0: ... print "x is zero" ... elif x < 0: ... print "x is negative" ... else: ... print "x is not a number" ... §1.9.2 ̂(for§while§break§continue§range() for̂Š{ for x in : else: • sequenceL«?Ûstring§tuple§dictionary >>> for x in "abc" : print x ... a b c >>> for x in [1,2,3]: print x ... 1 2 3 >>> D={"one":1,"two":2,"three":3} >>> for x in D: print "D[",x,"]=",D[x] ... D[ three ]= 3 D[ two ]= 2 D[ one ]= 1 • breakŠéŒ±r1òÑ̂§ÚC˜" annCharles@tom.com 129,208 Python ÆS)P ˜ Python0 • else´ŒkŒÃ"ek§KL«XJz‡a¥ƒÑ̂ (vkbreak)§@o ҉1else-block"ù˜:éЧϏ·3CŠó¥§²~‡ùoŠ" for(i=0;i>> a [1, 2, 3, 4] >>> for x in a: ... if x==100: break ... else: ... print "100 not found" ... 100 not found else ŠéŒ±n)µXĴvkbreak Šér1¥ä§½ö`̂~(å §Ò¬‰1else¥Šé"ù„´)MŠ{£ã§ŠÂ£ã¬\˜Ù§~Xþ ¡~f§¿g´`XJ3a¥éØ100§@oÒ¬‰1else¥Šé"ŠÂ3ˆ‡ þe©œ¹e¬k¤ØÓ"˜„œ¹e§breakѬ3˜‡if Šé¡3§elseÒ ´L«§XJ@‡if Šé3̂¥l5Ñvk¤áL§Ò¬‰1else ¥Šé" þ¡~f¥§if ^‡´x==100§@oXJa¥?¿ƒx§Ñknot x==100§@ oelse¥ŠéÒ¬‰1" • ?Ux¿ØU ?Ux3a¥éASN" >>> a=[1,2,3,4] >>> for x in a: ... x=x+1 ... >>> x 5 >>> a [1, 2, 3, 4] 3ÄK̂Ҕ¿Â annCharles@tom.com 130,208 Python ÆS)P §1.9 §S6§ 5¿§´ØU?Ux3a¥éASN§XJ´Dictionary§@ovk?Ux§ ´† ?UDictionary ¥SN"wLname space Vgúùég," >>> D={"one":1,"two":2,"three":3} >>> for x in D: ... D[x] += 1; ... >>> D {’three’: 4, ’two’: 3, ’one’: 2} e‡?U§Ò^range()¼ê"range([start,]stop,[,step])§L«lstartm©§ stop(å§zÚO\step§start"Ž0§step"Ž1§ˆ£˜‡list" >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,10,2) [1, 3, 5, 7, 9] >>> range(1,10,-1) [] eŒU)Á‡ê§@o´˜list§Ø¬kk̂" |^range()¼ê?Ulist >>> a [1, 2, 3, 4] >>> for x in range(len(a)): ... a[x]=a[x]+2 ... >>> a [3, 4, 5, 6] >>> whilêŠ{" while : else: annCharles@tom.com 131,208 Python ÆS)P ˜ Python0 ù ‡ Ì ‚  ¿ g ´ §  ‡expr1´ ý § @ o Ò ˜ † ‰ 1block¥  Š é "XJ vbreakaÑ̂§Ò´`§3̂(åžÿexpr1´b§@o‰1else-block¥ Šé" >>> i=0 >>> while i < 3: ... print i ; i=i+1 ... 0 1 2 >>> while i < 3: ... print i; i = i +1 ... else: ... print i , "is 3" ... 0 1 2 i is 3 ZO# i=i+1§ÄKÒ¬kk̂" §1.10 ¼ê ¼ê´˜㌱­E¦^“è" §1.10.1 ļê^{ Š{: def ( ): `²: • function_name´¼ê¶¡§kÒ^5©…¼êSN" • parameters_list´ëêL"ëêvka.§Œ±D4?Ûa.Š‰¼ê§d ¼êSN½Â¼ê§XJD4ëêa.Ø´¼êŽ‡§@o¼êŒ± ÑÉ~" • code block´Úif§while˜“è"5¿ATkƒÓ ?" annCharles@tom.com 132,208 Python ÆS)P §1.10 ¼ê • ¼êvkˆ£Ša.§returnŒ±ˆ£?Ûa." ~f: >>> def add(a,b): ... return a+b; ... >>> print add(1,2) 3 >>> print add("abc","def") abcdef >>> print add("abc",12) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in add TypeError: cannot concatenate ’str’ and ’int’ objects >>> myadd=add >>> myadd(1,2) 3 ¼ê¶¡´˜‡Cþ§˜‡é–"P“˜ƒÑ´é–”"¤±Œ±”ÊÏ閘§ r˜‡¼êDŠ‰,˜‡Cþ"myadd=add§ùk:”¼ê"⊉function alias§ ¼êO¶" §1.10.2 ëê‡êŒÀ§ëêk%@Š PC++§VB¥ŒCëê§Python˜kaqś"~f: >>> def myjoin(str,sep=","): ... return sep.join(str) ... >>> myjoin(["a","b","c"]) ’a,b,c’ >>> myjoin(["a","b","c"],";") ’a;b;c’ sep"ŽŠ´“§”§^ÏÒ©§XJvkJøsepëê§@o§Ò^“§”"´XJ˜ ‡ë괌À§@o¦¡¤këêÑAT´ŒÀëê" >>> def myrange(start=0,stop,step=1): ... print stop,start,step ... annCharles@tom.com 133,208 Python ÆS)P ˜ Python0 SyntaxError: non-default argument follows default argument §1.10.3 UC¼êëêDŠ^S XJ½Â ˜‡±þŒÀëê§5´ØUUCëêD4^S§ >>> def printValues(name,height=170,weight=70): ... print("%s’s height is %d cm," ... " his weigth is %d kg\n"%(name,height,weight)) ... >>> printValues("Charles") Charles’s height is 170 cm, his weigth is 70 kg >>> printValues("Charles",175) Charles’s height is 175 cm, his weigth is 70 kg >>> printValues("Charles",175,85) Charles’s height is 175 cm, his weigth is 85 kg >>> ´Œ±ÏLe¡ªUCëê^S" >>> printValues("Charles",weight=85) Charles’s height is 170 cm, his weigth is 85 kg §1.10.4 ‡êŒCëê XJ^LCŠó¥printf()§@oÒ¬éëê‡êŒC¿Â' )"¦+ŒÀë êś-¼êëê‡ê´ŒC§´„´k›§ëê‡êkŒ›§ …„‡ ²= ´ŒÀëê" e¡ù‡Å›§Œ±É?¿õ‡ëê" >>> def printf(format,*arg): ... print format%arg ... >>> printf ("%d is greater than %d",1,2) 1 is greater than 2 Ù¥*arg7L´˜‡ëê§*L«É?¿õ‡ëê§Ø c¡ëê§õ{ ëêъ˜‡tupleD4‡¼êprintf§Œ±ÏLarg5–¯" >> def printf(format,*arg): ... print type(arg) ... print format%arg >>> printf("a",1) annCharles@tom.com 134,208 Python ÆS)P §1.10 ¼ê 3¼ê¥§arg ´˜‡tuple§Œ±ÏL–¯tuple{§5–¯arg" „k˜«ª5¢y?¿‡êëê§Ò´ëêUìdictionaryªD4‡¼ê§¼ê ÓŒ±É?¿õ‡ëê" >>> def printf(format,**keyword): ... for k in keyword.keys(): ... print "keyword[%s] is %s"%(k,keyword[k]) ... >>> printf("ok",One=1,Two=2,Three=3) keyword[Three] is 3 keyword[Two] is 2 keyword[One] is 1 Óþ˜«Å›aq§ØL**keyword´^**L«É?¿‡êk¶iëêD4§´ N^¼êž§‡²ëê¶i§One=1,Two=2,Three=3§3¼ê¥§Œ±^dictionary ª5öŠkeyword§Ù¥keys´["One","Two","Three"]§values´[1,2,3]"„Œòü« śÚ3˜å"ùž§*arg§‡˜3**keywordc¡" >>> printf("%d is greater than %d",2,1,Apple="red",One="1") 2 is greater than 1 keyword[Apple]=red keyword[One]=1 „Œ±rùü«Å›ÚŒÀëêśÜ3˜å¦^" >>> def testfun(fixed,optional=1,*arg,**keywords): ... print "fixed parameters is ",fixed ... print "optional parameter is ",optional ... print "Arbitrary parameter is ", arg ... print "keywords parameter is ",keywords ... >>> testfun(1,2,"a","b","c",one=1,two=2,three=3) fixed parameters is 1 optional parameter is 2 Arbitrary parameter is (’a’, ’b’, ’c’) keywords parameter is {’three’: 3, ’two’: 2, ’one’: 1} ¼êÉëê^S§kɽëê§,´ŒÀëê§,É?¿ë꧁´‘¶ i?¿ëê" annCharles@tom.com 135,208 Python ÆS)P ˜ Python0 §1.10.5 Doc String ¼ê£ã ò© 3§Sp§´LISP¥˜‡AÚ§Python/L5"z‡¼êÑ´˜ ‡é–§z‡¼êé–Ñk˜‡__doc__á5§¼êŠé¥§XJ1˜‡Lˆª´˜ ‡string§ù‡¼ê__doc__Ò´ù‡string§ÄK__doc__´None" >>> def testfun(): ... """ ... this function do nothing, just demostrate the use of the ... doc string. ... """ ... pass ... >>> print testfun.__doc__ this function do nothing, just demostrate the use of the doc string. >>> passŠé´˜Šé§ŸoØZ§Ò”CŠó¥{}"ÏLw«__doc__§‚Œ± w˜ SܼêÏ&E" >>> print " ".join.__doc__ S.join(sequence) -> string Return a string which is the concatenation of the strings in the sequence. The separator between elements is S. >>> print range.__doc__ range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. ^ù«{§ wÏ§´›©k"© Ú§S3˜å§kÏu±© Ú§S˜— 5" §1.10.6 lambda¼ê ÙGfunctional programming < § Ø ¬ élambda¼ ê a  ))"LISP´ ˜ «functional programming language"ØÙGfunctional programming  < § Œ ± @ annCharles@tom.com 136,208 Python ÆS)P §1.10 ¼ê lambda¼êÒ´˜«{ü]¶¼ê" >>> f = lambda a,b: a+b >>> f(1,2) 3 >>> f("abc","def") ’abcdef’ f dudef f(a,b): return a+b" ˜‡¼êŒ±ˆ£˜‡lambda¼ê"X >>> def incfun(a): ... return lambda x: x+a ... >>> incfun(2)(12) 14 >>> incfun(2)(13) 15 >>> incfun(4)(13) 17 >>> §1.10.7 ¼êŠ^(scope) ùpP4˜‡LGB5K§python˜‡Cþ¶ikélocal name space (ÛÜ· ¶˜m)§3églobal name space(Û·¶˜m)§,´buildin name space (S3·¶˜ m) ^globalŠéŒ±UC, Cþ·¶˜m" >>> a=1 >>> def testfun(): ... a=2 ... print a ... >>> testfun() 2 >>> a 1 3¼êtestfun()¥a´3local name space ¥§?UaجUCglobal name space ¥a  ´§^globalŠéŒ±?U˜‡Cþ¤3name space" >>> a=1 annCharles@tom.com 137,208 Python ÆS)P ˜ Python0 >>> def testfun(): ... global a ... a=2 ... print a ... >>> testfun >>> testfun() 2 >>> a 2 >>> §1.10.8 i@¼ê(nested) Python¥¼ê´Œ±i@" >>> def outfun(a,b): ... def innerfun(x,y): ... return x+y ... return innerfun(a,b) ... >>> outfun(1,2) 3 ù3CŠó¥´Ø#N§ÏC¥static ¼êŒ±“Où«õU"ù«Å›Jø ˜‡ ¼ê‰ŒVg§, ¼ê3, ¼êSܧâw§XJ¦‡úm{§Œ±ÏL ˆ£Š§ˆ£Sܼê"5¿§ÚPascal ؘ§i@¼êØU–¯ ¼êCþ"· @i@¼ê^?،" §1.10.9 functionëêD4 python´UŠD4ë꧴„´kŒUUCëꤍŠ" >>> def change(x,y): ... x=2 ... y[0]="hello" ... >>> x=1 >>> y=[1,2] >>> change(x,y) annCharles@tom.com 138,208 Python ÆS)P §1.11 ¬(module)ڝ(package) >>> x 1 >>> y [’hello’, 2] Œ±w§xŠvkUC§´yŠ%UC "30 name space Vg¬úù ´3g,ØL¯œ "ëêx§y ØL´3function local name space ¥M# name §Úfunction N^öD?5ëꍕӘ‡é–"3function SÜx=2§´U C name xbind 'X§4ù‡name •˜‡#é–"¤±Ø¬KN^öD?5 ëꤍé–" y[0]="hello" ¿vkUCy bind 'X§ ´†?Uy¤•é –§@o,Ò¬UCN^öD?5ëê "w ¡name space Vg¬éù‡k n)" §1.11 ¬(module)ڝ(package) §1.11.1 Mmodule ˜‡module ØL´˜ ¼ê§class˜3˜‡©‡¥"~X§3c8¹(current direc- tory)M©‡testmodule.py§SN´ """ this only is a very simple test module """ age=0 # a sample attribute def sayHello(): # a sample function in a module print "Hello" if __name__ == "__main__" sayHello() ˜‡module kaqfunction doc string"Ø 5º1˜^ŠéXJ´˜‡iÎ G{§@où‡iÎGÒ´doc string§Œ±w˜‡doc string5Ï"import ˜ ‡module kü«{" >>> import testmodule >>> print testmodule.__doc__ this only is a very simple test module >>> Œ±–¯testmodule¥attribute annCharles@tom.com 139,208 Python ÆS)P ˜ Python0 >>> testmodule.age 0 >>> testmodule.age=1 >>> testmodule.age 1 >>> testmodule.sayHello >>> testmodule.sayHello() Hello >>> sayHello=testmodule.sayHello >>> sayHello() Hello >>> sayHello >>> >>> othermodule=testmodule >>> othermodule.age=100 >>> testmodule.age 100 Œ ± w  § ÏLmodname.attribute  ª Œ ± – ¯ §module ¥ attribute § 3module ¥½ÂCþ§¼ê§class Ñ´module attribute "^name space Vg 5)ºÒBõ §module ¥name space ¥˜ƒÑ´module˜‡attribute§‡L5 `module attribute ´module name space ¥˜‡name" sayHello=testmodule.sayHello()§ Œ ± 3global name space ¥ ï á ˜ ‡name§map(N  ) testmodule name space ¥  ˜ ‡name ¤  object" Œ ± w  ü ‡sayHello  • Ó ˜ ‡function object" ¦ + ¦ ‚  Ñ ´sayHello§ ¦ ‚   • Ó ˜ ‡ é – §  ´ ¦ ‚ 3 ü ‡ ØÓ name space ¥ "module    ´ ˜ ‡object§testmoduleÒ ´ ¦ name§ Œ ± 3global name space ¥ ï á , ˜ ‡name Útestmodule•Ó˜‡object§˜‡module object"othermodule = testmodule"XJ ˜‡module¥kéõk^functions§´ÏLmodulename.funcnameª§Òwé æ†"Œ±^1«import module {"­#?\python§," >>> from testmodule import age, sayHello >>> age 0 >>> sayHello annCharles@tom.com 140,208 Python ÆS)P §1.11 ¬(module)ڝ(package) >>> sayHello() Hello >>> testmodule Traceback (most recent call last): File "", line 1, in ? NameError: name ’testmodule’ is not defined >>> Œ±w§ù«{ƒu import testmodule age=testmodule.age sayHello=testmodule.sayHello ´k ØÓ§^from  {§testmodule ù‡¶i§¿vkimport ?5§ Ò ´ ` §  cname space ¥ v ktestmodule ù  ˜ ‡name§ import testmodule Ò Œ ± 3  cname space ¥ M ï ˜ ‡testmodule ù  ˜ ‡ name" Œ ± ^ from testmodule import * òtestmodule ¥name space ¥ ¤ kname Ú?   c name space ¥§ÏLù name§–¯name¤é–" …import testmodule § XJtestmodule.py?UL § Œ ± ^reload(testmodule)­#\1testmodule" §1.11.2 Noémodule python^±eÚ½阇module§±import testmodule~f" • 3c8¹¥étestmodule.py" • evé§3‚¸Cþ(environment variables) PYTHONPATH¥é§Ò–3PATH¥ 錉1©‡˜" • e ÃPYTHONPATHC þ § @ o 3 SC 8 ¹ ¥  é § 3unix ¥ ´.:/usr/local/lib/python Ù¢§python´3sys.path¥¤k8¹¥émodule"Œ±wsys.path" >>> import sys >>> print sys.path [’’, ’/usr/lib/python2.2’, ’/usr/lib/python2.2/plat-linux2’, ’/usr/lib/python2.2/lib-dynload’, ’/usr/lib/python2.2/site-packages’] lé^Sþw§·‚Œ±XJ\3c8¹ïá ˜‡ÚIO¥¥‘kI OmodulekƒÓ¶i@o¬^\module “OXÚmodule§¬)#¶Ù©¯K§¤ ±·‚‡5¿§gCmodule ¶i؇ÚXÚmodule¶iƒÓ" annCharles@tom.com 141,208 Python ÆS)P ˜ Python0 §1.11.3 package() package ´˜|module 8Ü"^±e{Mpackage" • y3c8¹M8¹testpackage • 3testpackage M˜©‡__init__.py • 3testpackage ¥Mtestmodule"py§p¡¹k˜ “è"ùp {ü§Ò Útestmodule.py˜" åÄpython >>> import testpackage.testmodule >>> testpackage.testmodule.sayHello() Hello package ´ ˜ « | „module   { § J ø ˜ ‡name space§ “ Ž u ) ¶ i À â"package ¥„Œ±kpackage§¤±ù«ªŒ±éÐ|„˜‡äG(§^5+ nmodules" §1.12 name space(·¶˜m) 3c¡0 ¥§ØŽ˜gJname space§y0 name space Vg§ù´˜‡ p?Vg§´XJn)¦§éõÀÜÑéN´n)"Ӟ¬aúpython ´˜«/ª {ü§Vg˜ß§VgژŠó" Ÿo´name space? name space ´l¶¡(name)é–(object)þN(map)"˜ ‡name N˜‡object þž§·‚`ù‡name Úù‡objectk½(bind)'X§½ö` ù‡name •ù‡object" ­E`§python ¥˜ƒÑ´object §)function §module §class §package  "ù objectsÑk3S¥ýý3§Ò”)¹3­þz˜‡<"´·‚ Noéù objectsQ? ^name! ‰z‡object 凶i"z‡name éA˜‡object ˜‡objectŒ±kõ‡¶i"´name Ø´object §Ò–˜‡<¶iCharles§ ´Charles Ø´ù‡<§´ù‡<¶i§ù‡<´kÉkS¬á§Charles Ø ¬§Charles´Œ±3’þ"˜‡<Œ±kõ‡¶i" Python¥kéõname space§~^k: build-in name space (S3·¶˜m) global name space (Û·¶˜m)§local name space(ÛÜ·¶˜m)"3ØÓname space ¥name ´˜:'Xvk"$–i¡þƒÓname§‡¦‚3ØÓname space ¥§@o¦‚ÒÎÃ'é"UClocal name space ¥namebind 'X§Ø¬Kglobal name space ¥ƒÓname" z‡object ÑkgCname space"Œ±ÏLobject.name ª–¯object name space ¥name"z‡object name space ´Õá"“Õᔿg´`§˜‡object annCharles@tom.com 142,208 Python ÆS)P §1.12 name space(·¶˜m) name space ¥˜‡name§ÚÙ§name space ¥name ´˜:'Xvk§$– ü‡i¡þwå5˜name§´Î؃Z"Ҕ“f” ù‡object§3¦name space ¥k˜‡“ôÚ”§ù˜‡name §L«˜‡fôÚ§ “’f”ù‡object §3 ¦name space ¥k˜‡“ôÚ”§ù‡name L«’fôÚ§¦Úf˜:'Xv k§¦+¦‚Ñ“ôÚ”" ·@¦+name space ´˜‡p?Vg§´¦´é˜ßVg§˜‡N´n)V g"{üVg¡ÛõXŒ¯"name space ´ù‡)P¥`õ§Û˜‡V g"·@§¦´python Ø%Vg§Ò”file ù‡Vgunix ¥˜" z ˜ ‡object § Xmodule§class§function§ ˜ ‡instance § Ñ k g C name space"name space ´ÄMï"z˜‡name space )žmØ˜" ˜‡module name space ´ù‡module import žÿMï" k˜‡AÏmodule §˜?\python)ºì§Òïá ˜‡module§ù‡module name space Ò´global name space§˜‡ۍ˜name space"ù‡module ˜‡S Üattribute§__name__ ^5I£module§ù‡module__name__ ´__main__" >>> print __name__ __main__ z˜‡module Ñk˜‡__name__attribute§^5L«cmodule ¶i"¤±z ˜‡module Ñkù“è" if __name__ == "__main__" sayHello() # ÿÁ“è ^ umodoule ÿÁ"Ϗ3˜‡module 3importžÿ§¦name space ¥Mï ˜ ‡ S ˜ name§__name__§ ^ 5 L«module  © ‡ ¶ ¡" ¤ ± 3 import  ž ÿ § ÿ Á “ è Ò – Ø  3 ˜  § Ï __name__§ [  Ø ¬ ´“__main__”"  ´ X J^python testmodule.py ª†$1˜‡module žÿ§ Ø´import§@ omodule name space Ò´global name space , ùžpython gÄrglobal name space ¥__name__ “__main__”§@oҌ±$1ÿÁ“è " ˜‡N^˜‡functionžÿ§functionlocal name space Mï §functionˆ £žÿ§½öfunction Ñexceptionžÿ§local name space íØ " >>> def testfun(): ... print locals() ... print globals() ... >>> >>> testfun() annCharles@tom.com 143,208 Python ÆS)P ˜ Python0 {} {’__builtins__’: , ’__name__’: ’__main__’, ’testfun’: , ’__doc__’: None} >>> locals()Úglobals()© O ˆ £global name space Úlocal name space"name space Ï ~ ^dictionary 5 L« §dictionary ´ ˜ ‡(key§name)ù  pair  8 Ü §key ´name§value´name ¤object" Ÿo´scope(Š^)? scope Ò´python ¥“èli¡¿Â(textually)þŒ±“† –¯”name 8Ü"ùp)ºü‡Vg: •“†–¯”¿g´^unqualified reference name Ҍ±†éname ¤é–" • unqualified reference Ҵعk.name"a Ò´˜‡unqualified name§a.b ÒØ ´" LGB 5 K ^scope V g 5 ) º Ò ´: 3 ?Û “ è ‰ 1  ž ÿ § Ñ –  k n ‡scope§˜‡´local name space |¤scope"˜‡´cmodule global name space |¤scope§„kbuildin name space |¤scope"lS g阇unqualified name"L local§G gloabl§B buildin" globalŠéŒ±UCr˜‡unqualified name scope§†global name space ¥ é" function alias ¿g´alias=module_name.funcname ªMfunction O¶" >>> def sayHello(): ... print "Hello" ... >>> saidHello=sayHello >>> saidHello >>> sayHello >>> sayHello() Hello >>> saidHello() Hello Œ±wsayHello§saidHello¦‚ØL´ü‡¶i§¦‚´Óobject"Җ˜ ‡>> a=1 >>> a 1 >>> del a >>> a Traceback (most recent call last): File "", line 1, in ? NameError: name ’a’ is not defined íؘ‡Cþ¿g´lSÜname space ˜Ø˜‡name Úobject ½(bind) 'X§ XJvkÙ¦nameÚù‡é–bind§@oâýíØobject"ùÚjava ¥-ãÂk aq"ÚCÚC++¥œUEâé”" ¢Spython ¥Ò´¦^ œUEâ§z‡name Ñڍ•objectƒ' é§z˜‡objectÑk˜‡referece counter P4kõ‡name Úù‡object bind"z gbind§reference count Ñ\1§zgíØbind 'X§Ñ~1§kreference counter C ¤0žÿâýíØé–" python ´˜«ra.§Äa.Šó" ra.´§z˜‡é–Ñk˜‡a.Xtuple §dictionary §list §string §int §long §float §module §function §class §methord Ú?Û^r½Â½ömodule ½Â class"Basic ÒØ´˜«ra.§¤±BasicN´Úåܧ~X print "1" + "2" 12 print 1 + "2" 3 N"1"+"2"§\Ï"´"3" ½ö"12"§´tØÃ\.‡Ÿo" z‡é–ÑkgCÕáname space"z«a.kgCÕáöŠ{"é–name space ¥name ¬Ú,‡öŠ{ƒéA"Cþ==´é–¶i" Ä  a . ´  z ‡ C þ ÑØ ^ ( ² § Œ ±  • ?Û a .  é – " ½ ö  C þ(variable)¶i(name)Ü·"Cþ´˜‡é–¶i§z‡Cþ3,˜ž •˜‡é–§´˜‡é–Œ±Óžkõ‡Cþ•¦§Ò”¼ê§module §class ь± kalias (O¶)"Cþ)χÚé–)ϴؘ"vk?ÛCþ•˜‡é annCharles@tom.com 145,208 Python ÆS)P ˜ Python0 –žÿ§ù‡é–âýíØ" ˜‡CþŒ±‘žUC¦½'X§=•Ù¦ é–" ù«LˆªÚ·‚y¢­.´˜—" Ÿo´nest function: nest function 3function SܽÂfunction é–"outer funci- ton ´½Âfunction function "inter function ´½Âfunction " outer function Úinner function vkŸ«O§´²'X§outer function local name space 3inner function ¥´ØŒ„" inner function ´outer function SÜMobject §•inner function name 3uouter function local name space " outer function Œ±ÏLˆ£Šś§rinner function ³‰N^ö" §1.13 a ¡ • é –(OO)´ ˜ «? § g Ž Ø ´ ˜ « Š ó "Python´ ^CŠ ó ´ ¢ y  ¡ • é –  Š ó "GTK ´ ^C   ¡ • é –  | ‡ ¥ "Unixö Š XÚ ¥ §“˜ ƒ Ñ ´ © ‡”§ ,«¿Â þ ù § ´ ˜ « ¤ õ  ¡ • é – § © ‡ Ò ´ ½  é Aopen§write§read§close§ioctrl ˜|Sؼê(½ö{)é–" ¡•é–8´“è­^§~­E5mu"¡•é–´“è­^ś)µ C(encapsulation)§U«(Inheritance)§õ(Polymorphism)" ¡•é–Ø%´Ä–(abstraction)§©l(interface)Ú¢y(implemetation)" §1.13.1 Ÿo´object ˜ƒÑ´object ! 3Python ¥§object ˜ck\2¹Â§3Ù§Šó¥§XC++ ¥§object ´˜ ‡class instance "´3Python ¥§object ˜ƒ§)§class, module, package, int, float, list, tuple, dict, function, class instance ژƒ^r§S¥½ÂÀÜ" )A‡Vg: name space name space ´name Úobject ƒmN'X"z˜‡name ˜ژ ‡object ”½"˜‡object Œ±kõ‡name "XJvkname Úobject ”½§@ oobject Ò¬ž” "name space ´˜‡Äêâ(§dictionary " objname = object ¬Mname " name name ´˜‡iÎG§•˜‡object "name ´name space ¥˜‡ƒ" object object ´˜‡Õáname space "object name space ^dictionary L«"õêœ ¹e§obj.__dict__ L«˜‡object name space "Ù¥obj.__dict__.keys() L «¤kname list §obj.__dict__[name] L«name ¤object " annCharles@tom.com 146,208 Python ÆS)P §1.13 a alias XJü‡name •Ó˜‡object §@oùü‡name palias " attribute name ©  ü « § ˜ « ´unqualified name § ˜ « ´qualified name "X Óobj.attr /ªname Ò´qualified name "XÓobj /ªname Ò´unqualified name " Attribute Ò´qualified name ¥“.” ¡Ü©" • Mïattribute {: obj.new_attribute = other ½ö setattr(obj,"new_attribute",other) • íؘ‡attribute {: del obj.old_attribute ½ö delattr(obj,"new_attribute") • Θ‡attribute {µ hasattr(obj,"new_attribute") • ¤kattribute {µ dir(obj) kéŠ5¿˜:§setattr, getattr, delattr ¥1‡ë괘‡string §XJ Ž~f¥^~þN^§ÒvkŸo7‡ §^éA1˜«ªŒÖ5¬Ð§ ´¦‚Œ±ÉëêCþ§Ò´§S3$1žÿŒ±?nattribute " ˜‡object name space ¥˜‡name ˜½´object ˜‡attribute "´˜ ‡object attribute ؘ½3object name space ¥" ˜‡object name space {´vars(obj) §˜‡object ¤kattribute  {´dir(obj) " ÑÚobject ˜§ù Vgk\2¹Â§'ß3éõPython ŠÂ¥" ~X: ¼ê3ëêD4žÿ§´UŠD4§O(/`§D4´˜‡alias " def func(a) : return a+1 x=1 func(x) annCharles@tom.com 147,208 Python ÆS)P ˜ Python0 func /ªëê´a §N^func(x) žÿ§¢Sëêx §ü‡name §¦‚palias " UŠD4¿g´`UC/ªëêŠØ¬K¢Sëê"´“UC/ªëꊔ ´aqa=2 UC§´4/ªëꍕ#閧´UC /ªëꔽ'X" XJé/ªëêöŠ§Xl.append(1) §@oUCØ´/ªëê§ ´/ªë ꤍé–" XJ ü ‡name p alias § @ o ¦ ‚ A  ˜  ˜  § Ò ” Ó ˜ ‡ < k ü ‡ ¶ i"function object alias ˜Œ±N^"´'…‡©˜ŸožÿUC´name §ŸožÿUC´name ¤object " Ò“=” ¿g§Ø2´DŠ§ ´4name •#object "4 module object SܽÂCþ§¼ê§aÑ´module object name space ¥object " function object ½Âi@¼ê§´N^žÿ§3local name space ¥ÄMï˜ ‡function object "ùÒn)§Ÿoinner function ØU–¯outer function local name space " §1.13.2 Ÿo´class oject ˜‡{üclass object" >>> class SimplestClass: ... pass ... ¦ŸovZ§´·‚Œ±gÍ`§·k ·1˜‡class object" we¡~fµ >>> class SampleClass: ... def __init__(self): ... print "OK, I was born." ... >>> a=SampleClass() OK, I was born. >>> AClass = SampleClass >>> b=AClass() OK, I was born. >>> 4 XJ´D[1]=something §@oL«N^D. setitem ¼ê annCharles@tom.com 148,208 Python ÆS)P §1.13 a class SampleClass '…i3cname space ¥)¤˜‡name §SampleClass § •˜‡class object " ¦¡ŠéÑ´Œ±‰1Šé"Údef ØÓ´§3)¤class object žÿ§$ 1¦¡Šé§ù Šé¥)¤˜ƒobject §Ñ3class object name space ¥"Œ± ^SampleClass.var1 /ª–¯class object name space ¥object" ù ŠéÏ~Ñ´˜ {üDŠŠé§Údef Šé§^u3class object name space ¥Mïobject " ~f¥§AClass = SampleClass Ҕfunction alias ˜§ïá ˜‡class alias" class object ̇Š^Ò´^5Mïclass instance " class object ´Œ±”¼ê˜N^§N^žÿ§Ñ\ëêҴЩz¼ ê__init__ ëê"Ù¥1˜‡ëêself Ø^Ñ\§Python ¬gÄ\þù‡ëê" N^(J´ˆ£˜‡class instance "~X: obj=ClassName()" 3ù˜:þ§class object Úfunction object aq§¦‚Ñ´callable "Œ±^¼ êcallable() 5u˜‡é–´Ø´Œ±N^" XJ˜‡class object ¥­1 Aϼê§@o¦)¤class instance ´callable " 3PythonvkC++¥E¼ê5 ÚÛ¼ê"´kЩz¼ê§˜‡objectMï ±§¬gÄN^__init__ §Ù8Ø´ M閧 ´ Щz˜‡é– ¥êâ" E¼êÚЩz¼ê´k«O§E¼êN^žÿ§é–„vkMï§Ò ´`§E¼ê´3Mïé–L§¥N^"´3Python ¥§é–Mïƒâ¬N^ Щz¼ê§Ò´`§3N^Щz¼êžÿ§é–®²Mï " class object Úmodule object kaq/"class object Úmodule object ': ƒƒƒÓÓÓ::: class object Úmodule object ¥Ñ¹kŒ±$1Šé"ù ŠéÏ~Ñ´˜ { üDŠŠé§Údef Šé§^5½ÂCþ§¼ê" class object Úmodule objet Ñ´˜‡Õáname space "Ù¥¹éõ½ÂÐname Úobject "ù object Ï~´function object " module object ¥~~¹class object "class object ¥Œ±i@½Âclass object " class object Úmodule object ˜ §1˜‡string Lˆª ´doc string "Œ± ^__doc__ –¯" ØØØÓÓÓ::: class object Úmodule object ŒØÓÒ´§class object Œ±^¼êN^/ª 5M#class instance" 53new style class ¥kE¼ê annCharles@tom.com 149,208 Python ÆS)P ˜ Python0 )¤module object {´M±“.py”(—©‡")¤class object {´ ¦^class '…i" 3cname space ¥Mïmodule object {´¦^import Šé"module 1 ˜gimport ½öreload žÿ§$1Ù¥Šé" 3cname space ¥Mïmodule object {´¦^class Šé"$1ù^Šé žÿ§¬^S$1class object ¥Šé§3Ùname space ¥Mïobject " §1.13.3 property Úmethord ùp¦^property Úmethord ü‡âŠ§´Ï¦‚^õ "3Python ¥§5 vkùü‡Vg" ÃØ´property „´methord Ñ´attribute "property ´data attribute §methord ´function attribute " c¡`L§˜‡object name space ¥˜‡name ˜½´object ˜‡attribute " ´˜‡object attribute ؘ½3object name space ¥"ù´Ï§attribute ´Uì ±e5K|¢ 1˜‡name " 1. |¢object name space 2. XJobject ´˜‡class instance §|¢object ¤áclass object name space " 3. XJobject ´˜‡class object §Ý`k|¢object ¤kykname space " 4. XJobject k__getattr__ ¼ê§N^ù‡¼ê§¦^ˆ£(J" Uìe–“è£ãŽ{ def search_name(obj,name): #1. |¢ object  name space if name in obj.__dict__: return obj.__dict__[name] else: try: # 2. XJ object ´˜‡ class instance § # |¢ object ¤á class object  name space " return search_class(obj.__class__,name) except AttributeError: if obj.has_attr(__getattr__): #4.XJ object k __getattr__ ¼ê§N^ù‡¼ê§¦^ˆ£(J return obj.__getattr__(name) annCharles@tom.com 150,208 Python ÆS)P §1.13 a else: raise AttributeException, "%s not found"%name def search_class(clsobj) # 3.XJ object ´˜‡ class object §Ý`k|¢ # object ¤kyk name space " if len(clsobj.__bases) == 0: if clsobj.has_attr(__getattr__): return clsobj.__getattr__(self raise AttributeError, "%s not found"%name for base in clsobj.__bases__: return search_name(base,name) ˜ ‡class object  __bases__ § L« ¦  ¤ k †  I a " ˜ ‡class instance __class__ §L«Mï¦class object " ~X: class A: # ˜‡{üa a=1 # a ´ A ¥ name obj = A() print vars(obj) # ‹< obj  name space, #ÑÑ{}, Ϗ obj  name space ´˜ print dir(obj) # ‹< obj  ¤k attribute , # [’__doc__’, ’__module__’, ’a’] #Ϗ attribute |¢Ž{ obj.a=2 # M attribute print vars(obj) # ÑÑ{’a’: 2} print obj.a # ÑÑ 2,k3 obj  name space ¥éa" del obj.a # íؘ‡ attribute print obj.a # ÑÑ 1,3 A  name space ¥é a " A.a = 100 # UCA ¥ a obj =A() # Mï#é– print obj.a # ÑÑ 100,§3 A  name space ¥é a " del obj.a # )É~"Ϗ obj ¥vk a " print obj.b # )É~"attribute |¢Ž{Ã{éb" A.b = 200 # 3A¥Mïb print obj.b # ÑÑ 200 "attribute |¢Ž{3A¥éb" annCharles@tom.com 151,208 Python ÆS)P ˜ Python0 class instance obj Úclass object ,AÑkgCÕáname space §Ò”¤kobject ˜§¦ ‚ÑŒ±Õá‘žï᧑žíØÙname space ¥name " class instance obj Úclass object ,A 5´Õá§vk'X§´attribute  |¢Ž{r¦‚éX3˜å" attribute |¢Ž{rIaÚfaéX ˜å§ù¢y U«Å›" z˜‡a¢~Ñk˜‡attribute §‰__class__ §3%@œ¹e§ dir Ø ÑÑù‡attribute §¦´Œ±^" ØÓclass instance kgCÕáname space "~X: >>> class B: ... def __init__(self): ... self.a=1 ... >>> obj1=B() # Щz¼êz˜‡ instance Mï a >>> obj2=B() >>> obj1.a # obj1 Ú obj2 ¥Ñk 1 # a >>> obj2.a 1 >>> del obj2.a # íØ obj2 ¥ a >>> obj2.a # vk ,ØU3^ obj2.a Traceback (most recent call last): File "", line 1, in ? AttributeError: B instance has no attribute ’a’ >>> obj2.b=1 # M obj2.b >>> obj2.b # obj2 k b, vk a 1 # obj1 k a, vk b ¦+¦‚Ó´ # class B  instance §1.13.4 bound methord Úunbound methord 3|¢˜‡object attribute žÿ§XJattribute ´˜‡function object §@oÒ ‡kAÏ?n§rù‡function object C¤bound methord ½öunbound methord " bound methord Úunbound methord «O bound methord ژ‡class instance ”½" unbound methord Øژ‡class instance ”½" annCharles@tom.com 152,208 Python ÆS)P §1.13 a bound methord ¬gÄrclass instance Š1˜‡ëꧤ±N^žÿ‡D4˜ ‡ëê" unbound methord Kج§N^žÿ§ØUD4˜‡ëê" ~X: class A: def h(self): pass a=A() Ù¥§a.h ´bound methord "A.h ´unbound methord " N^bound methord {´ a.h() §D˜‡ëêself §^a “Oself "51 ˜‡ëꌱ´?Û¶i§Ø˜½š‡´self §´ù´˜‡éÐS." N^unbound methord {´A.h(a) §ØUDëê" ·‚Œõꜹ¦^bound methord §œ¹¦^unbound methord " ¦^unbound methord ;.œ¹Ò´§N^Iaunbound methord " bound methord Úunbound methord ƒÓ: ¦‚1˜‡ëêÑ´˜‡class instance §ù‡class instance Úmethord ÓáuӘ ‡class object " ¦‚Ñ´class object name space ¥function object §˜„Ø´class instance name space ¥name §Øš²w3class instance name space ¥MӶ name " bound methord §unbound methord ÚÊÏfunction object ' ùp¤`ÊÏfunction ´3class Šé››‰Œƒ ½Âfunction object " • ƒÓ: ¦‚Ñ´function object §Ÿþ˜"methord ƒéuÊÏfunction 5`§3? nclass instance Úclass object žÿ§¿vkŸoؘA"=¦´ bound methord ½öunbound methord §class object name space ¥§¦Š^S§ ؝¹class object ¥name §Ò´`§¦ÚÊÏfunction æ^˜ LGB { K§Ï阇name " Python ¥vkÙ¦Šó¥aqthis ½öme Cþ"z‡methord §Ñ´class object ˜‡attribute §¦‚Â1˜‡ëêÒ´self "¦ÚÊϼê˜§Ñ‡Ï Lself 5–¯class instance attribute "¦ÚÊϼ꘧ь±class instance Mï§íØattribute " annCharles@tom.com 153,208 Python ÆS)P ˜ Python0 • ØÓ: XJbound methord ½öunbound methord ¤áclass object ´AObj §@omethord 1˜‡ëê7L´AObj class instance ½öAObj fšclass instance "ÊÏ function object vkù‡›" §1.13.5 U«(inherit) U«Š{‚ª´ class (superclass1,superclass2,...): Œ ± k õ ‡ I a " – ¯ I a methord   ~ ^   { ´ ¦ ^unbound methord§superclass.methord(self,...)" z˜‡ class object Ñk˜‡__bases__ attribute §´˜‡tuple §^uP¹¦ ¤k†IŠ" attribute |¢Ž{¢y U«ś" AØ^”C++ ¥@AO)ºŸo´­1§ attribute |¢Ž{®²`² ˜ ƒ" Šâattribute |¢Ž{§¬k±e­1Jµ 1. ˜‡class instance  name space ¥name ¬“O¦ class object ¥Ó¶ name §Äk|¢" 2. ˜‡ class object name ¬“OIa¥Ó¶name §Äk|¢" ´3õ­U«žÿ§Ò´`§kõ‡Iažÿ§‡5¿Ia3½Â¥Ñy^ S§Ï¦Šâattribute |¢Ž{û½ ÒIaƒm­1'X"¡¬k\\ ?Ø" §1.13.6 ·¤ Cþ N\^LC++½öJava¥·¤ Cþ§Ò´Ó˜‡class ØÓinstance Ó˜ ‡Cþ"python kù«Å›§´§Ø´Ú?#ÀܧϏz‡class instance k˜ ‡obj.__class__ attribute •Mïclass instance class object "|^ù˜:§·‚Œ ±¢y·¤ CþõU" >>> class A: ... count = 0 ... def __init__(self): ... self.__class__.count= self.__class__.count + 1 ... #5¿Ø´self.count annCharles@tom.com 154,208 Python ÆS)P §1.13 a >>> A.count #„vkA instance 0 >>> a=A() # MA instance >>> a.count # a.count Ú A.count ´3ü‡ØÓ name space ¥ 1 >>> a.count = 2 # UC a.count >>> a.count 2 >>> A.count # جK A.count 1 # y3A k˜‡instance >>> a.__class__ # a name space k˜‡ __class__  name >>> a.__class__ is A # ù‡ name ÚAÑÚӘ‡ class é–kbind 'X. 1 # Ò´`,¦‚´˜£¯,´Ó˜‡ÀÜ >>> b=A() #3M instance >>> A.count # __init__ ¥ self.__class__ O\ 1 2 # self.__class__ ÚA ´Ú˜ÀÜ. # y3 Akü‡ instance . §1.13.7 Abstrace Class Java kinterface §C++ ¥abstract class §@opython Qº class AbstractClass: def AbstrctMethord(self): raise NotImplementedError Ø É~exceptionƒ §vk0 #Vg"Ӟ÷v abstract class ‡¦"ÐÆ¡ •é–?§§úù´Ã“觟ovkZ§ÆLƒ§uyù´¡•é–Ø%g Žƒ˜§©lÚ¢y" §1.13.8 hkattribute XJ3class object ¥½Â¶i÷ve¡^‡µ 1. ±ü‡ey‚“__” mÞ" 2. õ±˜‡ey‚“__” mÞ" ùattribute §Ò´hk" ¢yhkattribute {§âŠ‰name mangle " annCharles@tom.com 155,208 Python ÆS)P ˜ Python0 ¯¢þ§Python ¥vk{¢yýhkattribute §Python ¢y{ØL´U ¶i ®§‡3½Âclass object ¥Šé¥-÷vþ¡^‡name §Python ÑgÄ \þ“_classname” § ~X: >>> class A: ... __prv_a=100 ... >>> vars(A) {’__module__’: ’__main__’, ’_A__prv_a’: 100, ’__doc__’: None} >>> A._A__prv_a=200 >>> vars(A) {’__module__’: ’__main__’, ’_A__prv_a’: 200, ’__doc__’: None} 5¿__prv_a C¤ _A__prv_a "ù‰JÒ´“Ž ¿ –¯ IaÓ ¶attribute " ´§3§S¥„´kŒU–¯hkattribute "þ¡~f¥Ò´–¯hkattribute {"¦^ù«{3NÁ§Sžÿ´ék^" ؚ¿ùo‰§ÄK–¯hkattribute Ŭ´§ù«Å›Œ±3,«§Ý þ“Ž§S ‹†Ø" §1.13.9 Python ¥class AÏmethord e¡AÏ methord Œ±­1§¢yaq C++ ¥öŠÎ­1õU" 3Python ¥kéõclass AÏmethord§”__init__Ò´Ù¥˜‡" •__init__ ®²0 L §Ò´3obj=A_Class(arg,...)žÿgÄN^§§ëêØ self „kA_Class ¥D4ëê" •__del__(self) 3é–íØžÿ§gÄN^"Ò´`vkname Úù‡object kbind 'Xžÿ§¬N^¦" •__repr__(self) ¦^repr(obj) žÿ§¬gÄN^obj __repr__ ¼ê§ù‡ ¼ ê ˆ £ Úeval() o N  é – i ÎGL ˆ ª § ^ u ­ ï é – §  Ò ´ ` § X Jeval(repr(obj)) ¬˜‡é–€" •__str__(self) ‘Bˆ£˜‡iÎG£ãé–"e¡~f`² __repr__ Ú__str__ ØÓ" >>> class A: ... def __repr__(self): ... return "A()" annCharles@tom.com 156,208 Python ÆS)P §1.13 a ... def __str__(self): ... return "ok, I am here" ... >>> x=A() >>> print x ok, I am here >>> print repr(x) A() >>> b = eval(repr(x)) >>> b A() >>> eval(str) ´^5OŽ˜‡python Lˆª§¿…ˆ£ù‡Lˆª"ù´)ºŠóÏ^ A5§Œ±3§S¥§S§´rù«“è€È¤C++ ´'(J§ÏI‡ k)º‰1Lˆª¬"ùŒØ´˜‡N´óŠ" •__cmp__(self,other) ˜‡'öŠÎ"0 L«ƒ§1L«Œu§−1L«u" >>> class Dog: ... def __cmp__(self,other): ... if other > 0 : return 1; ... elif other < 0 : return -1; ... else: return 0 ... >>> dog = Dog() >>> if dog > -10 : print "ok" ... >>> if dog < -10 : print "ok" ... ok >>> if dog == 0 : print "ok" ... ok >>> ùã“萴`²__cmp__ ^{§Ù¢ù´é·Ï˜ã“è§ÚêikŸoÐ '? ¦´`² pythonŠóA:§ÒŽÆ¬ ˜€Šó§˜¬ŠÃÔ g" annCharles@tom.com 157,208 Python ÆS)P ˜ Python0 •__hash__(self)§ˆ£˜‡32 hash value"­1ù‡¼êƒ§ù class instance Ҍ±Š dictionary êâ(¥key " •__nozero__(self)§±c·‚5¿None§"" §() ÑL«Ü6b§Ù¦Ñ´ ý§Ù¢Øé§ùpŒ±½Â˜‡é–´Ä´Ü6b"XJˆ£0 L«Ü6b§ ˆ£1 L«Ü6ý" >>> class Dog: ... alive=0 ... def __nonzero__(self): ... if self.alive==0 : return 0 ... else: return 1 ... >>> dog = Dog() >>> dog.alive 0 >>> if dog : print "the dog is alive" ... else: print " the dog is dead" ... the dog is dead >>> dog.alive =1 >>> if dog : print "the dog is alive" ... else: print " the dog is dead" ... the dog is alive >>> ùã“èwå5'þ˜‡~f„´N´Ã"–¦vk`l" •__len__(self)§3^S˜¼êlenN^é–žÿ§¬N^§ˆ£objectÝ" XJvk½Âù‡¼ê§ N^len(obj)¬—É~" >>> class EmptyClass: ... pass ... >>> obj=EmptyClass() >>> len(obj) Traceback (most recent call last): File "", line 1, in ? AttributeError: EmptyClass instance has no attribute ’__len__’ >>> class Dog : annCharles@tom.com 158,208 Python ÆS)P §1.13 a ... def __len__(self): ... return 1000 ... >>> dog = Dog() >>> len(dog) 1000 c¡˜Ü©`² vk½Â__len__ ¬—É~§¡~f`² ½Â __len__ Ҍ± §„´ `²Šó§ ˜ã æ“è§No¬kÝ Qºlen(dog)˜‡Ý?ÎÿÂ"´3\kùo˜«Å›Œ± ‰ݧN\3mu˜‡EmailBody class žÿҌ±^len(a_email_body) ˆ£˜‡>fe‡SNÝ"¡„¬˜ ÿ“觐´ `²Šó A:" •__getitem__(self,key)§ˆ£self[key] ^5[list§dictionary§tuple êâ( " >>> class Zoo: ... def __getitem__(self,key): ... if key == "dog" : return "dog" ... elif key == "pig" : return "pig" ... elif key == "wolf" : return "wolf" ... else : return "unknown" ... >>> zoo=Zoo() >>> zoo["dog"] ’dog’ >>> zoo["pig"] ’pig’ >>> zoo["wolf"] ’wolf’ 5¿§__getitem__ Œ±¦˜‡é–”sequence ˜"3python ¥⊴§object ¢y __getitem__ protocol (Æ)§aqjava ¥interface"Ò´`˜ S˜Š é§for ¬¦^ùÆ" >>> class A: ... def __getitem__(self,key): ... print "debug: key is %s"%key ... if key >=0 and key <=5: return key * key annCharles@tom.com 159,208 Python ÆS)P ˜ Python0 ... raise IndexError ... return None ... >>> a=A() >>> for k in a: print k ... debug: key is 0 0 debug: key is 1 1 debug: key is 2 4 debug: key is 3 9 debug: key is 4 16 debug: key is 5 25 debug: key is 6 >>> raise IndexError ´L«(å"return None Cvk^ "for Šél0 m©§ ^˜‡Øä4Okey la ¥é–"^while£ã¦Ò´ __tmp__ = 0 while(1): try : k = a[__tmp__] ... # for SŠé __tmp__ = __tmp__ +1 except IndexError: break ù´ `² for k in a ŠÂ§,^for Šé\{ö"\[ج¦^ù «whileŠé“Ofor Šé" •__setitem__(self,key,value)§[ obj[key]=value" >>> class A: ... def __setitem__(self,key,value): annCharles@tom.com 160,208 Python ÆS)P §1.13 a ... print "debug: you want to set [%s] to [%s]"% ... (key,value) ... >>> a=A() >>> a["key"]="value" debug: you want to set [key] to [value] >>> •__delitem__(self,key)§[ del obj[key] ž§N^T¼ê >>> class A: ... def __delitem__(self,key): ... print "debug: you want to del [%s]"%(key,) ... >>> a=A() >>> del a["key"] debug: you want to del [key] __delitem__§__setitem__§__getitem__ ´Jø˜«*Ða.Š{§äNŠ §ATd\§Sû½§Œ±´Ð§S§Œ±Ñ4>> class A: ... def __getslice__(self,i,j): ... print "you want to get the slice %d:%d"%(i,j) ... def __setslice__(self,i,j,value): ... print "you want to set the slice %d:%d to %s"% ... (i,j,value) ... def __delslice__(self,i,j): ... print "you want to del the slice %d:%d"%(i,j) ... >>> a=A() >>> print a[1:2] you want to get the slice 1:2 None >>> print a[:] you want to get the slice 0:2147483647 annCharles@tom.com 161,208 Python ÆS)P ˜ Python0 None >>> a[2:3]= [1,2] you want to set the slice 2:3 to [1, 2] >>> del a[:] you want to del the slice 0:2147483647 >>> •__contains__(self,other) Œ±¦object ”sequence ˜§?nin Šé >>> class A: ... def __contains__(self,other): ... if other=="ok" : return 1 ... return 0 ... >>> a=A() >>> if "ok" in a: print "ok in a" ... else : print "ok not in a" ... ok in a •__call__(self,arg1,arg2,...) 4object ”¼ê˜§Œ±N^" >>> class A: ... def __call__(self,*arg):#ùp¦^ŒCëêś,‹<¤kD?5ë ê ... for k in arg: ... print k ... >>> a=A() >>> a("hello","World") hello World >>> • Ù¦ŽâöŠÎ§XL1.13-4 kéõ¼ê¢y öŠÎ­1ś§A¤kpython öŠÎÑkù«­1ś" \Œ±˜‡gCclass §4¦wå5§”list §dictionary ˜§|±¤klist  ¤köŠÎڊé"3python module lib ¥®²kùclass§Œ± w¦‚ annCharles@tom.com 162,208 Python ÆS)P §1.13 a { (J __add__(self,other) self + other __sub__(self,other) self - other __mul__(self,other) self * other __div__(self,other) self / other __mod__(self,other) self % other __divmod__(self,other) divmod(self,other) __pow__(self,other) self ** other __pow__(self,other,modulo) pow(self,other,modulo) __lshift__(self,other) self << other __rshift__(self,other) self >> other L 1.13-4: Œ±­1ŽâöŠÎ¼ê “觚~᧴ékdŠ"3lunix ¥Œ±3/usr/lib/python2/ ¥éUserList.py UserDict.py" §1.13.10 ˜ AÏ­1¼ê^{Þ~ |^ bases class á5‹>> s = ’abc’ >>> it = iter(s) >>> it >>> it.next() annCharles@tom.com 169,208 Python ÆS)P ˜ Python0 ’a’ >>> it.next() ’b’ >>> it.next() ’c’ >>> it.next() Traceback (most recent call last): File "", line 1, in -toplevel- it.next() StopIteration ½Â˜‡|±S“ìclass object é{ü"­1__iter__() §ˆ£˜‡object§ù‡ é–|±next() attribute "XJclass object knext {§@o__iter__() Œ± ˆ£gC" ~f: #itertor1.py class Container: def __iter__(self): return TestIter(0,5) class TestIter: def __init__(self,start=0,end=10,step=1): self.start=start self.end = end self.step = step def next(self): if self.start == self.end: raise StopIteration try: return self.start finally: self.start = self.start + self.step if __name__ == "__main__": c = Container() for i in c: print i annCharles@tom.com 170,208 Python ÆS)P §1.13 a $1(J: 0 1 2 3 4 try ... finally Šé´É~?nŠé" ù‡~f¥^ˆ£˜‡#閧TestIter(0,5) §ù‡é–|±next() attribute " e¡ù‡~f¥§__iter__() ˆ£é–§ é–q|±next() {"Œ± ÓJ" #itertor1.py class Container: def __iter__(self): self.index = 0 return self def next(self): if self.index == 5 : raise StopIteration try: return self.index finally: self.index = self.index + 1 if __name__ == "__main__": c = Container() for i in c: print i S“ìŠ^´©lH{Ž{ÚNìêâ("kNìêâ(´éE,§~X ä§Üêâ("H{Ž{´õ«õ§¦^S“쌱ÛõŽ{[!§4¦^ ö±Ú˜/ªN^"ù«{4§SLˆCé{'§˜—" \½Â˜‡Lˆä(žÿ§Œ±½ÂØӐ{§ˆ£ØÓS“짢yØ ÓH{ª" for node in tree.leftfirst(): print node for node in tree.rightfirst(): print node annCharles@tom.com 171,208 Python ÆS)P ˜ Python0 ´§Ï~½Â˜‡S“ìžÿ§Ñ‡¦^˜‡Cþ5±c ˜§~Xþ¡~ f¥self.count self.index §ŒU„‡k˜‡ýêâN짌±^self.index l ¥ýk^閧 Ø´{üself.index §ÄK^range ¼êҌ± " XJ\‡S“ì´é{üŽ{§„‡½ÂAOCþ§self.index §AO¼ êself.next ÚÑÉ~raise StopIteration §ùÒéæ† §Ï\S“ìŽ{ ´Xd{ü§Ø–u‹ÄZ{§¤±e¡ù‡{AOk^§âŠ)¤ìGenerator" ~X: def gen(): yield 1 yield 2 yield 3 yield 4 g = gen() print g.next() # ‹< 1 print g.next() # ‹< 2 print g.next() # ‹< 3 print g.next() # ‹< 4 print g.next() # ÑÉ~ ¦^yield ŠéŒ±MGenerator"yield ŠéUÑy3¼ê¥"XJ˜‡¼ ê¥kyield Šé§@où‡¼êÒ‰generator "- yield Šéƒ§¼êˆ£˜ ‡iterator §¿…P4v &E§P‰¥ä:"|^ù &E§§SŒ±l¥ä:?­# $1§ 3¦^iterator žÿ§XJN^next() {§@oÒ¬Òl¥ä:?­#$1" XJgenerator ¼êˆ£ §ÒgÄÑStopIteration É~" 3list comprehension ś¥§¢SŒ±^S“ì"~X: >>> x = [ i*i for i in gen()] >>> x [1, 4, 9, 16] w,˜‡~f: #generator1.py def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] annCharles@tom.com 172,208 Python ÆS)P §1.13 a for char in reverse(’golf’): print char $1(J´: f l o g '…3uyield Šé§¦¿g´`§ 1. ff?\̂žÿ§Ð©N^reverse()" 2. reverse() ¥‰1yeild Šéžÿ§reverse() 6ʧˆ£˜‡êâé–" 3.  for ê⧉1for ̂NSŠé§?1?nêâ" 4. ˜Ó̂(僧lyield 6Ê/§UY‰1reverse() ¥Šé"XJq-  yield Šé§@o2‰±þöŠ" 5. †reserver()ˆ£§for Šéâ~(å" 3zgI‡N^next žÿ§Òˆ£yield Šé¡Lˆª§§S6ʧ,for ¥ ŠéUY$1§eg2I‡next žÿ§¬UYlyield 6Ê?§UY$1§†yield #êâ§2UY‰1" ù«Lˆª¬3¼êˆ£žÿgÄÑStopIteration É~"  [yield Šé^{§e¡~f‰ ˜ ?U§´O\ ˜ ‹<Š é§^u`²§S‰1^S" #generator2.py def reverse(data): print "reverse begin" for index in range(len(data)-1, -1, -1): print "begin yieding " + str(index) yield data[index] print "end yieding " + str(index) print "reverse returned" for char in reverse(’golf’): print "begin getting a char " print char print "end getting a char" annCharles@tom.com 173,208 Python ÆS)P ˜ Python0 $1(Jµ reverse begin begin yieding 3 begin getting a char f end getting a char end yieding 3 begin yieding 2 begin getting a char l end getting a char end yieding 2 begin yieding 1 begin getting a char o end getting a char end yieding 1 begin yieding 0 begin getting a char g end getting a char end yieding 0 reverse returned XJ3for ¥- break Šé§@o§SÒØ2£yield 6Ê/§ ´†a Ñ̂§‰1̂¡Šé "~X: #generator3.py def reverse(data): print "reverse begin" for index in range(len(data)-1, -1, -1): print "begin yieding " + str(index) yield data[index] print "end yieding " + str(index) print "reverse returned" for char in reverse(’golf’): print "begin getting a char " annCharles@tom.com 174,208 Python ÆS)P §1.13 a print char if char == ’l’ : break print "end getting a char" $1(J: reverse begin begin yieding 3 begin getting a char f end getting a char end yieding 3 begin yieding 2 begin getting a char l §1.13.11 new style class new style class ´Python 2.2 #JÑõU"Ïdƒéunew style class §þ¡0 class object §‰classic class " XJ˜‡class object yk´“object” §@où‡class object Ò´new style class " “object” ´˜‡class object ¶i"Ò´`§XJ˜‡class object †U«½öm U«“object” §@oÒ´new style class " †U«new style class ~X: class newClass(object) mU«~fX: class newClass(dict) "Ù§Xint, float, list, dict, tuple, file  §Ñ´“object” fa" new style class äkclassic class ¤kA5" k¡X­0 new style class Úclassic class ØӃ?" O\ ü‡#methord ś static methord we¡~f" class AClass(object): def astatic( ): print ’a static method’ astatic = staticmethod(astatic) anInstance = AClass( ) AClass.astatic( ) # prints: a static method anInstance.astatic( ) # prints: a static method annCharles@tom.com 175,208 Python ÆS)P ˜ Python0 3½Â¼ê§¦^Šé astatic = staticmethod(astatic) Œ±Mstatic methord " class instance Úclass object ь±N^static methord §J˜" static methord ÚÊÏfunction Avk«O" class methord we¡~f" class ABase(object): def aclassmet(cls): print ’a class method for’, cls._ _name_ _ aclassmet = classmethod(aclassmet) class ADeriv(ABase): pass bInstance = ABase( ) dInstance = ADeriv( ) ABase.aclassmet( ) # prints: a class method for ABase bInstance.aclassmet( ) # prints: a class method for ABase ADeriv.aclassmet( ) # prints: a class method for ADeriv dInstance.aclassmet( ) # prints: a class method for ADeriv `²: class methord Úbound methord aq"bound methord ´gÄrclass instance Š1˜‡ëê"class methord ´gÄrclass object Š1˜‡ëê§ Ø´class instance " ÃØ´clsInstance.class_methord /ª§„´clsObject.class_methord / ª§J˜" O\ #Aϼê new __init__ ´Ð©z¼ê§Ø´E¼ê"3N^__init__ ¼êžÿ§é–® ²MïÐ "#O__new__ ¼ê§´ýE¼ê" clsInstance = clsObject(...) du clsInstance = clsObject.__new__(clsObject,...) 5¿§__new__ 1˜‡ëêØ´˜‡class instance § ´˜‡class object "¦% @Ò´˜‡˜‡class methord §Ø^¦^ annCharles@tom.com 176,208 Python ÆS)P §1.13 a __new__ = staticmethod(__new__) 5AO(²¦´˜‡class methord " object.__new__ %@Ċ´M閧,N^__init__ §ˆ£˜‡class instance " ­1__new__ žÿ§¬~~N^Ia(Xobject, list, tuple, dict, file ) __new__ ¼ê§,§2ŠÙ¦\‡Z¯œ" ˜‡;.~fÒ´ˆ£˜‡®²3閧¢ySingleton design pattern "~ fµ class Singleton(object): _singletons = { } def _ _new_ _(cls, *args, **kwds): if not cls._singletons.has_key(cls): cls._singletons[cls] = object._ _new_ _(cls) return cls._singletons[cls] ù‡~f¥§Singleton z˜‡fša§Uk˜‡é–§Ò´`§XJclsobj1, clsobj2, ..., clsobjn , Ñ´Singleton fš"@oclsobj1 ¤kclass instance Ñ´ Ә‡object §clsobj2 ¤kclass instance ѴӘ‡object §... §clsobjn ¤ kclass instance ѴӘ‡object "ØÓfš§Xclsobj1, Úclsobj2 class instance شӘ‡object " getattribute __getattr__ ù‡Aϼê3attribute |¢Ž{¥§´˜'" #O__getattribute__ ´1˜'§Ò´¦¬:¤kattribute Ú^ž¦" new style class class instance A5 property attrib = property(fget=None, fset=None, fdel=None, doc=None) Œ±˜‡new style class instance O\˜‡attribute §‰attr " fget ´Öproperty žÿ§N^bound methord "ØÂëê"None L«property ،Ö"fset ´property žÿ§N^bound methord "˜‡ëê§L« \Ÿo"None L«property ،"fdel ´íØproperty žÿ§Ò´N^del obj.attr Šéžÿ§N^bound methord "ØÂëê"None L«property Ø Œí"doc L«doc string " ~f: annCharles@tom.com 177,208 Python ÆS)P ˜ Python0 class Circle (object): def _ _init_ _(self,radius): self.radius = radius def getArea(self): return self.radius * self.radius * math.pi def setArea(self,value): self.radius = math.sqrt((value/math.pi)) area = property(getArea,setArea,doc=’area of the circle ’) ù‡~f¥§XJc ´˜‡Circle ˜‡class intance "@o print c.area # N^ c.getArea c.area = 100 # N^ c.setArea(100) print c.area.__doc__ # ‹< area of the circle " __slots__ ´˜‡sequence (˜„´tuple )§Ù¥z˜‡ƒ´˜‡string "ù´˜‡ Jpǐ{"Ϗobject name space ´˜‡dictionary §´ÄžÚº˜ S§ùÇ$"k __slots__ ƒ§object name space Ò´˜‡½S Œ§Óž§object Øk__dict__ 5L«name space " object #ïattribute ¶i7L´__slots__ ¥¶i" ½Â__slots__ Øu½Âattributes , „‡MïƒâU^" ~f: slots — >>> class OptimizedRectangle(object): ... __slots__= ’width’,’heigth’ ... >>> r = OptimizedRectangle() >>> r.width # ½Â__slots__ Øu½Â attribute Traceback (most recent call last): File "", line 1, in ? AttributeError: width >>> r.width,r.heigth=1,2 >>> print r.width,r.heigth 1 2 >>> r.high = 100 Traceback (most recent call last): File "", line 1, in ? AttributeError: ’OptimizedRectangle’ object has no attribute ’high’ annCharles@tom.com 178,208 Python ÆS)P §1.13 a ù‡~f¥§Mïhigh ´Ø#N" __slots__ Çpś§´±ã+ÄMïattribute A5“d" k3S¥ÓžŒþ3ùclass instance žÿ§Œþ´Azùêþ ?§ Ø´AZ‡ùêþ?§ …z˜‡instance ‡!ŽA›‡i!§ùJp ÇJ²w"ÄKÒvk7‡ " new style class ¥¥¥Per-instance methords ˜‡class object ˜‡class instance Œ± ”½˜‡attribute ?¿˜‡function object " ~X: >>> class AClass: ... pass ... >>> a = AClass() >>> fakeGetItem=lambda idx:idx >>> a.__getitem__=fakeGetItem >>> a[100] 100 ù‡~f¥§a Œ±rAϼê__getitem__ §”½?¿˜‡¼êþ§´ù ž§a.__getitem__ Ø´˜‡bound methord § ´˜‡ÊϼꧏҴ`§¦Ø UgÄrclass instance Š1˜‡ëê" new style class Úclassic class 3?nÚ­1öŠÎƒ'N^Aϼêk¤ØÓ" new style class ´k3class instance ¤áclass object name space ¥|¢Aϼ ê§ Ø¬3class instance name space |¢" classic class „´Uì5|¢Ž{§vkŸoAÏ?n§Ò”þ˜‡~f" ~X: >>> class NewStyleClass(object): ... pass ... >>> a = NewStyleClass() >>> a.__getitem__=fakeGetItem >>> a[100] Traceback (most recent call last): annCharles@tom.com 179,208 Python ÆS)P ˜ Python0 File "", line 1, in ? TypeError: unindexable object >>> a.__getitem__(100) 100 Œ±w§öŠÎ­1žÿ§new style class ==¬3class object ¥|¢AÏ ¼ê"´§XJشϏöŠÎ­1§ †N^__getitem__ §„´ÚÙ ¦attribute |¢Ž{˜—" new style class õõõ­­­UUU«««››› list, dict, file 閡S˜é–"¦‚U«†¤ knew style class Äa“object”§3õ­U«¥§õUӞU«˜‡S˜é–Ú ˜‡“object” " new style class ÚÚÚclassic class methord |||¢¢¢^^^SSSØØØÓÓÓ classic Uìattribute | ¢Ž{§|¢˜‡methord "~X: class D: pass class B(D): pass class C(D): pass class A(B,C): pass Uì|¢Ž{§classic class |¢^S´A,B,D,C,D" class D(object): pass class B(D): pass class C(D): pass class A(B,C): pass new style class |¢^S´A,B,C,D,object "Ò´2Ý`k|¢" new style class ÚÚÚclassic class NNN^^^IIIaaa{{{ØØØÓÓÓ classic class ¥N^Ia{§ ˜„¦^unbound methord "~X: annCharles@tom.com 180,208 Python ÆS)P §1.13 a class A: def met(self): print ’A.met’ class B(A): def met(self): print ’B.met’ A.met(self) class C(A): def met(self): print ’C.met’ A.met(self) class D(B,C): def met(self): print ’D.met’ B.met(self) x=D() x.met() 3ù‡~f¥§B.met(self), C.met(self) Ò´unbound methord ^{"´¯K ´§ùA.met Ò¬N^üg" $1(J´: D.met B.met A.met C.met A.met new style class )û{Ò´§¦^super "super(clsobj,obj) ¬ˆ£˜‡AÏ clsobj Ia"·‚^ super(clsobj,obj).somemethord(...) |¢somemethord žÿ§|¢^SÚþ¡ù|¢^S´˜" ~X: class A(object): def met(self): annCharles@tom.com 181,208 Python ÆS)P ˜ Python0 print ’A.met’ class B(A): def met(self): print ’B.met’ super(B,self).met( ) class C(A): def met(self): print ’C.met’ super(C,self).met( ) class D(B,C): def met(self): print ’D.met’ super(D,self).met( ) x=D() x.met() $1(J´µ D.met B.met C.met A.met 3ù‡~f¥§super(D,self).met() |¢met ^S´B,C,A"ù§Òvkù ‡¯K "ïƱnew style class Ñ^ù«{N^Iamethord " §1.14 É~?n(exception) §1.14.1 Ÿo´É~?n§Ÿo‡kÉ~?n É~?n´˜«Ñ†?nś"˜½‡éц?n‰upÝ­À§˜‡rFS §S “襧¿÷ ц?n§XJ؇ц?n§@o “è5¬éõ"\Œ ±é˜‡‘8~f§wwp¡kõŒ'~ “è´Ñ†?n§„kõŒ'~´NÁ“ è"\ŒU¬uyýZ¹“èÓé'~"Ҏ˜‡~$1§S§¦ŒÜ©ž m$1“萴\¤“è¥4˜Ü©"´ØUvkù “触‚Ò–ž“ §²ž¿vkl¯)óŠ§vkMEdŠ§´ØUvk¦‚§?Û<Ñž“è ­‡5"C ¥†Ø?n{´ int fun1() annCharles@tom.com 182,208 Python ÆS)P §1.14 É~?n(exception) { ... if ( open(...) == -1 ){ return -1; } ... } int fun2() { ... if (fun1()==-1){ return -1; } ... } int main() { ... if(fun2()==-1){ return -1; } } lù‡~f¥§·‚Œ±wCŠóц?nk‡±eA‡A:µ • §Sz˜?ч‰Ñ†?n§^5r†ØÏþ˜?¼ê" Ϗ.¼êØATNo?n†Ø§k¼êN^ö§Ò´þ˜?¼êâU §¤±7Lù˜?˜?þ" ù‘5¯K´§?Ñ´äц§“èŒÜ©Ñ´Ñ†?n" • §SÏLˆ£Š5L«†Ø" ù‘5¯K§ˆ£ŠkÜÂ"ˆ£ŠØ‡ˆ£~§SŽ‡ê⧄‡ˆ £†ØG§ù§§S“kŒU”¬r†ØG¤ˆ£êâ5?n"~X: unsigned int r; r=read(fd,buffer,len_of_buffer); for(i=0;i>> def fun(): ... try: ... print "ok" ... return 1 ... finally: ... print "clean up" ... return 1 ... >>> fun() ok clean up 1 >>> ù«{·Üuº˜] "XJ˜‡¼êkõ‡/return @o҇3z˜‡returnƒc ?AÓº˜] “è§X'4©‡§'4äë"finally {Jø ˜‡3¼êˆ£ƒc§‰1˜ “è§5'4] §¼êˆ£ŒU´Ïreturn Šé§½ öu) vkÓ¼exception §1.14.3 Ñexception raise Šé^uÑexception§3Ñexception žÿ§Œ±´?Ûobject§^u [£ã†Øa." >>> from UserList import * >>> try: ... raise UserList([1,2]) ... except UserList,arg: ... for k in arg: print k ... 1 2 annCharles@tom.com 188,208 Python ÆS)P §1.14 É~?n(exception) 3except ¥‡exceptionTypeÚobject a.˜—§ÒŒ±Ó¼ù‡exception "a. ˜—¿g´object ´‰a.˜‡instance"XJ˜‡object ¤áclass U« Ù¦ class§@où‡object Œ±´õ‡a.instance§ù a.)object ¤áclass I a§IaIa§IaIaIa... except ØŒ±½exception a.§„Œ±ÂÑ5object" þ˜‡~f¥arg Ò´raise ŠéÑ5UserList([1,2]) ù§ÒŒ±k´L& EŒ±^5£ãцÏ"˜„5`§Ñ´ÑException Ú§fa§lÃþ¥Œ± éõException a.§X: KeyError§IndexError§IOError "´pythonŠ óvk›§\Œ±Ñ?Ûa.é–"^rŒ±gCMException fa§5 L«^rf½Âexception"raise Šé„Œ±´raise classname,objectname/ª§ Ù¥objectname Œ±Úclassname vk˜:'X§,ù‰éزœ§˜„classname Úobjectname„´k'X§^5L²\§S¥Ü6'X" classname éAexcept Šé¥exception a.§objectname éAexcept Šé¥ arg >>> try: ... raise KeyError, "hello" ... except KeyError, arg: ... print arg ... hello Œ„§ÑÚÓ¼exception Jø ˜«Bц?nś"¼êØ^3ÏLAψ£ Š5Ïþ˜?¼ê£¼êN^ö)u) †Ø§ ´ÏLraise exception ª" ˆ£ŠÒ´¼ê~ˆ£žÿATˆ£ÀÜ" ù«{Œ±\¯mu„ݧ3muÐϧŒ±Ø^?n?ۆا±\¯§S. mu„Ý" ~§S¥§¬kéõ“è´Ñ†?n§˜?˜??n"XJKù ?n§¬¦ §Swå5é˜Ù§² "˜‡¹éц?n§S.¥y‡^ržÿ§¦+¦ Ø´érF§´Œ±k˜‡ýŒ±¦^§SŠë§^5Â8^rI¦§÷^ rI¦§ùŒ±~‘8ºx" ƒ‡§XJ˜‡§Smu éȧ¹éõц?n§érF§´¥y‡r žÿ§%uy§5@Ø´rŽ‡§@´éßÔ§”“§L¤<åÔ寜" –uц?n§Œ±3±O\§Ï¼êˆ£ŠÚц?nvk'X§§SÌZ ´ØI‡UC§§S?n6§ØI‡Cz"Ò´`§Œ¢ÌN(´Ø^C§‡ ‰´V<\"·Žxx´kÓn§Ñ´kx‡Ó+§,2˜Ú˜Ú[z" annCharles@tom.com 189,208 Python ÆS)P ˜ Python0 XJvkexception ś{(~XCŠó)§\ÒI‡trace (|¢) .´=‡¼êˆ£ †Ø§ …´†Ø Þ§,3¤kN^ù‡¼ê/Ñ\ä§þ†ØŠ§XJ k ¼êk{ÏLˆ£Š5þ†Ø§~X§˜‡¼êˆ£Š´˜‡iÎ(byte§õ0 – 255)§L«,256 «~G§y3‡2O\eZGL«Ñ†§@o‡o?U¼êˆ £Ša.§‡oO\#ëê§^uˆ£†Ø"oƒ´I‡?U§¯¤±§?U ´§Smuý‰" Ñyù«¯KÏÒ´“ˆ£ŠØ==´ˆ£Š”" ^exception ś§ÒŒ±3I‡Ñ†?n/§O\try Šé"Җ´ž“è § @pk»Ò•=p§ Ø´3?ۘ‡ŒUX»/Ñ˜ž“è §@¬é@§\ XÚ¥ Œ±½Â˜‡region mÞ§region (—Ò´c1I  ˜"ù‡·-Œ±rregion ¥Ü©ux‰)ºì‰1"XJéÄ python )ºì§ @oÒ¬3Python )ºì¥‰1§Ò”˜‡˜‡·-Ñ\Ù¥˜" 4. C-c RET ½ö M-x py-execute-import-or-reload ù‡·-3mu¬L§¥AOk^§Œ±r3?6©‡Š˜‡module § \Python )ºì¥"mu¬žÿ§²~‡rù‡¬import ½öreload "k ù‡õU§@omu6§Ò´§?U¬§C-c RET §$1ÿÁ“è§UY?U ¬"ùŒŒJp mu„Ý"ù‡·-ÚC-c C-c ƒ'§kü‡`:" (a) ¤k¼êÚCþ½ÂÑ´3¬Sܧ Ø´)ºì¥ÛCþ" (b) Python NÁ쌱éA©‡1꧴u†Ø½ " 5. C-c C-s ½ö M-x py-execute-string ¬3minibuffer ž¦^rÑ\˜ãpython “è§,$1¦"ù3NÁ˜‡¼ê žÿ§ékÏ"\Œ±Ñ\¼ê¶¡§$1ù‡¼ê"½ö\é,‡¬¼ê ^{Ø’½§½öé,«Š{Ø’½žÿ§ŒéB$1{ü˜é{ “è"½öwÏ´ék^§Œ±$1help(somefunc) Œ±wÏ§½ö $1type(somevar) wa.§½ödir(obj) wé–¤ká5" 6. C-c C-# ½ö M-x comment-region Œ±rregion Ü©5ºK" M-x uncomment-region Œ±rregion Ü©5ºKÜ©§K5º"ùéNÁ§SékÏ" 7. C-c C-k ½ö M-x py-mark-block Œ±r1I¡˜|“謧IP˜‡region §1I¬£Ä“è¬mÞ"Œ ±^C-x C-x 5uregion mÞÚ(—" 8. C-M-a ½ö M-x py-beginning-of-def-or-class annCharles@tom.com 193,208 Python ÆS)P  muPython ¦^óä C-M-e ½ö M-x py-end-of-def-or-class ©OL«£Ä1I˜‡def ½class ¬mÞ½ö(—"Œ±¦^ëê"~X: C-u 1 C-M-a L«£Ä1Iþü?def ½class ¬mÞù‡·-A3Emacs ¤ k?§ª¥åŠ^" 9. C-M-h ½ö M-x py-mark-def-or-class L«r˜‡def ½öclass Šé¬§IP˜‡region "Œ±^C-x C-x 5uregion mÞÚ(—"ÓŒ±¦^ëê"ù‡·-A3Emacs ¤k?§ª¥åŠ ^" 10. C-c > ½ö C-c C-r ½ö M-x py-shift-region-right C-c < ½ö C-c C-l ½ö M-x py-shift-region-left ©OL«rregion •†£Ä§Ú•m£Ä§^5UC“謠?" 11. C-M-j ½ö M-x indent-new-comment-line 3?õ15ºžÿ›©k^§L«m©˜‡#1§gÄ\þ5ºÎÒÚ(  ?" 12. C-x $ ½ö M-x set-selective-display L«w«˜‡¬¥¤kaڼ궡§ ÛõaÚ¼êÌN§ùé^ w˜‡¬¥“èÓ+"ù‡·-´Œ±Éëê§~X: C-u C-x $ L«Û õ§C-x $ L«w«aÚ¼êÌN" 5ù‡õUØ´ù‡¿g§5¿g§w« ?Šu½ëê1"~ XC-u 4 C-x $ XJ˜1mÞ¹k˜‚êu4 §@oÒw«¦§ÄKÒØw «§C-x $ L«w«¤k1"TЧpython ¦^ ?5L«Š{(§¤±^ˆ‡ õUŒ±w “è(" š~Ð^! cÙ´\§S錞ÿ§iruÙm§‘qsÌ&Ú" §2.2 Ù¦?6ì Œ±3e¡Œ§wNõ?6ì§XJEmacs Ø·Ü\§ÒÀJ˜‡·Ü\ ?6ì" http://www.python.org/cgi-bin/moinmoin/PythonEditors ´§·rí¦^Emacs "Jý؆" annCharles@tom.com 194,208 Python ÆS)P §2.3 NÁ§S §2.3 NÁ§S NÁ§SÄípdb §¦´python f‘NÁ¬"aqGDB §©i.¡§Ø ´éÐ^"´¦´˜‡.e§kÙ§.¡Ð§S|^pdb 5NÁ§S"ØLw˜ epdb Ï„kék^" §2.3.1 ¦^DDD Úpydb NÁpython §S DDD ´˜‡Í¶ã/.¡NÁ§S§¦¦^.NÁóä§;.Ò ´GDB "  ÚDDD ܧpydb ´˜‡pdb U?‡" Uìe¡Ú½Œ±SCpydb Ú¦^DDD " 1. SCDDD §XJ\Unix ½öLinux muCé{§AT®²CÐ DDD "XJvk§wDDD SCÃþ" 2. e1pydb "·´l http://ftp.debian.org/debian/pool/main/p/pydb/pydb_1.01.orig.tar.gz e1"XJù‡ó”}{§\UéÐ/e1" 3. €pydb.py $PATH ¥˜‡8¹"Ò´`§Shell Œ±é¿…$1ù‡·-" ~X: $cp pydb.py /usr/bin/pydb 5¿‡U¶i§K.py *ж¡" 4. €pydbsupt.py Úpydbcmd.py §˜‡8¹§(import ·-Œ±é¦‚" ˜„´ $cp pydbsupt.py pydbcmd.py /usr/local/lib/python/ 5. $1 $ddd --pydb Ҍ±‹mã/.¡ " Œ±ÀJEdit/Preference.../Source èü§r“Refer to Program Source” ˜¤“by Full Path Name”§„Œ±U ?ŠÚ´Äw«1Ò" 6. ÀJFile/Open èü§‹m\‡ §S§ÒŒ±NÁ " Ϗ´ã/.¡§äNNÁ{§¹¢˜¬Ò¬ " annCharles@tom.com 195,208 Python ÆS)P n Python ~^¬ 111nnnÙÙÙ Python ~~~^^^¬¬¬ ¬Ø”Ø%Šó@o­½§ŒU¬C§Ò”g,ŠóŠ{´'­½§´ Ñ5©Ù(¢Z O"´k˜ ~^¬´'­½"XJùp0 Ú¢S ‡ؘ—§„´I‡w#Ãþ" §3.1 S˜¬ S˜¬´Ø^import Ҍ±†¦^"§¹kéõk^¼ê"ÞXe§äN Œ±Ãþ§½öprint obj.__doc__ wÏ" §3.1.1 ~^¼ê ~^S˜¼ê3L3.1-1¥" ~X: >>> help(dir) Help on built-in function dir: dir(...) dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the annCharles@tom.com 196,208 Python ÆS)P §3.1 S˜¬ help(obj) 3‚Ï§obj Œ±´?Ûa." callable(obj) ww˜‡obj´Ø´Œ±”¼ê˜N^ ¦" repr(obj) obj L«iÎG§Œ±|^ù‡iÎ G^eval ¼ê­ïTé–˜‡€ eval(str) str´˜‡iÎG§L«Ü{python Lˆ ª"ˆ£ù‡Lˆª dir(obj) wobj name space ¥Œ„name " hasattr(obj§name) w ˜ w ˜ ‡obj name space ¥ ´ Ä kname getattr(obj§name) ˜‡objname space ¥˜‡name" setattr(obj§name§value)  ˜ ‡obj name space ¥ name  •valueù‡object delattr(obj§name) lobj name space ¥íؘ‡name vars(obj) ˆ £ ˜ ‡object name space" ^dictionary L« locals() ˆ£˜‡ÛÜname space§^dictionary L « globals() ˆ£˜‡Ûname space§^dictionary L « type(obj) w˜‡obj a. isinstance(obj§cls) wwobj´Ø´clsinstance issubclass(subcls§supcls) wwsubcls ´Ø´supcls fa L 3.1-1: Python ­^S˜¼ê attributes of its bases. Otherwise: its attributes, its class’s attributes, and recursively the attributes of its class’s base classes. >>> callable(dir) #ŒN^ 1 >>> a=1 >>> callable(a) #،N^ 0 >>> a=dir #¼ê aliase ´ŒN^ >>> callable(a) 1 annCharles@tom.com 197,208 Python ÆS)P n Python ~^¬ >>> a(" ") #Údir(" ")˜" [’__add__’, ’__class__’, ’__contains__’, ’__delattr__’, ’__doc__’, ’__eq__’, ’__ge__’, ’__getattribute__’, ’__getitem__’, ’__getslice__’, ’__gt__’, ’__hash__’, ’__init__’, ’__le__’, ’__len__’, ’__lt__’, ’__mul__’, ’__ne__’, ’__new__’, ’__reduce__’, ’__repr__’, ’__rmul__’, ’__setattr__’, ’__str__’, ’capitalize’, ’center’, ’count’, ’decode’, ’encode’, ’endswith’, ’expandtabs’, ’find’, ’index’, ’isalnum’, ’isalpha’, ’isdigit’, ’islower’, ’isspace’, ’istitle’, ’isupper’, ’join’, ’ljust’, ’lower’, ’lstrip’, ’replace’, ’rfind’, ’rindex’, ’rjust’, ’rstrip’, ’split’, ’splitlines’, ’startswith’, ’strip’, ’swapcase’, ’title’, ’translate’, ’upper’] >>> repr({"one":1,"two":2}) # repr ^uiÎG§^5L«é– "{’two’: 2, ’one’: 1}" >>> a=[1,2] >>> eval(repr(a)) # eval Ú repr Œ±˜‡é–€" [1, 2] >>> a [1, 2] >>> hasattr(a,"append") 1 >>> getattr(a,"append")(3) >>> getattr(a,"append")(4) >>> a [1, 2, 3, 4] >>> type(a) §3.1.2 a.=†¼ê ~^a.=†¼êXL3.1-2 Þ~: >>> chr(65) ’A’ >>> [ord(k) for k in "ABC"] [65, 66, 67] >>> oct(65) , oct(65000),oct(650000000) (’0101’, ’0176750’, ’04657433200’) annCharles@tom.com 198,208 Python ÆS)P §3.1 S˜¬ chr(i) r˜‡ASCII ꊧC¤iÎ ord(i) r˜‡iνöunicodeiΧC¤ASCII êŠ oct(x) rêx C¤l?›L«iÎG hex(x) rêx C¤›8?›L«iÎG str(obj) obj iÎG£ã list(seq) r˜‡sequence =†¤˜‡list tuple(seq) r˜‡sequence =†¤˜‡tuple dict()§dict(list) =†¤˜‡dictionary int (x) =†¤˜‡integer long(x) =†¤˜‡long integer float(x) =†¤˜‡2:ê complex(x) =†¤Eê max(... ¦ŒŠ min(...) ¦Š L 3.1-2: a.=†¼ê >>> hex(65) , hex(65000),hex(650000000) (’0x41’, ’0xfde8’, ’0x26be3680’) >>> str(10),str([1,2]),str({"one":1}) (’10’, ’[1, 2]’, "{’one’: 1}") >>> list("abc"),list((1,2,3)) ([’a’, ’b’, ’c’], [1, 2, 3]) >>> tuple("abc"),tuple([1,2,3]) ((’a’, ’b’, ’c’), (1, 2, 3)) >>> dict(),dict([("one",1),("two",2)]) ({}, {’two’: 2, ’one’: 1}) >>> dict([ ( str(x), x) for x in [1,2] ]) {’1’: 1, ’2’: 2} >>> int(1),int("1"),int(1.4),int(1.6) (1, 1, 1, 1) >>> int("1.2") #Ø1, 1.2 wå5ؔê Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 1.2 >>> long(1),long("1"),long(1.4),long(1.6) (1L, 1L, 1L, 1L) annCharles@tom.com 199,208 Python ÆS)P n Python ~^¬ >>> float(1),float("1.2"),float("1e-4") (1.0, 1.2, 0.0001) >>> min(1,2,3,4,5) 1 >>> min([1,2,3,4,5]) 1 >>> max([1,2,3,4,5]) 5 >>> max(1,2,3,4,5) 5 §3.1.3 ^u‰1§SS˜¼ê \¬ import§\˜‡module" ‰1“è exec code [ in globaldict[,localdict]]" >>> exec "a=1" #3c namespace þ‰1“è. >>> a 1 >>> mynamespace={} #M˜dictionary,^u;namespace >>> exec "a=1" in mynamespace #3 mynamespace þ‰1“è. >>> print mynamespace.keys() #w(J [’__builtins__’, ’a’] #Ú\ü‡name >>> type(mynamespace["__builtins__"]) #e˜‡¯<~f >>> class A: #˜‡˜ class ... pass ... >>> exec "a=1" in vars(A) #O\˜‡á5 >>> A.a #¤õ 1 >>> exec "def abc(self): print ’ok’ " in vars(A) # „UO\˜‡ methord >>> dir(A) #5¿,k abc annCharles@tom.com 1100,208 Python ÆS)P §3.1 S˜¬ [’__builtins__’, ’__doc__’, ’__module__’, ’a’, ’abc’] >>> x=A() >>> x.abc() #¤õ ok >>> ù«ª´é(¹ÚrŒ§´¦éJ€È¤C++ ½öJava Šó"ؚ§\( ½^Python Š§SmuÌNŠó§ …éPython 5Uék&%§ØŽ^Ù§Šó XC++ ­, õU¬"Ÿo¬^C++ ­§ Ø´†^C++ Q? ù9˜ ‡^‡ó§‘K"{ü/`§^C++ ŒU†§ºxŒ"Python ŒU†§´ ºx"C++ þ5Ò°H[§(JŠ¬ŒUØ´^r‡"Python ´ƒ£§^rŒ ±kw˜‡Ó+§,2°H[T§^C++ ­, ¬" ˜«´ÎÙ.§¬Úåºx\O§˜«´S“.§ÅÚ[z§º˜ºx" ^C++­´Ãã§Ø´8§8´÷vrI¦"XJŒ±÷v^rI¦§ÒØ ^­" ҎØU÷v^rI¦§Ø‡:X?U§kÿþ§ww5U´¶3=p§k ˜¥§O\ߧ¤ éõåí§5UvkUCõ§ ØØvó§python kprofile module ^uOŽpython §S¥zã“è5U"é“´¶”§(@“´¶”§,`z" ?ȓè compile§XJ˜ã“è²~‡¦^§@ok?ȧ2$1¬¯" >>> c=compile("print ’hello’","abc","single") >>> exec c hello >>> c=compile("raise 1 ","abc","single") >>> exec c Traceback (most recent call last): File "", line 1, in ? File "abc", line 1, in ? # 5¿©‡¶´ abc TypeError: exceptions must be strings, classes, or instances, not int compilekn‡ëê§1˜‡“èiÎG"´éAPython §S©‡¶¡§¦^u3 ‰1“è§)É~žÿ§‹<ц&E"1n‡ëê´“single”§“exec” “eval”nöƒ ˜§ùûu“è´á=‹<(JŠé§„´˜|Šé§„´˜‡Lˆª"e¡~f' ?ÈÚØ?È5U O" >>> code="print ’Hello World’" annCharles@tom.com 1101,208 Python ÆS)P n Python ~^¬ >>> c=compile(code,"abc","exec") >>> profile.run("for i in range(10000): exec c") 10002 function calls in 0.250 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.090 0.090 0.250 0.250 :1(?) 10000 0.160 0.000 0.160 0.000 abc:1(?) 1 0.000 0.000 0.250 0.250 profile:0(for i in range(10000): exec c) 0 0.000 0.000 profile:0(profiler) >>> profile.run("for i in range(10000): exec code") 10002 function calls (2 primitive calls) in 0.720 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 10001/1 0.720 0.000 0.720 0.720 :1(?) 1 0.000 0.000 0.720 0.720 profile:0(for i in range(10000): exec code) 0 0.000 0.000 profile:0(profiler) Œ±w§˜‡´0.250‡CPU seconds§˜‡´0.720 CPU second"Œ±Jp5UŒ3 " OŽLˆª eval(str) ^uˆ£˜‡Lˆª"5¿LˆªŠ{ڊéŠ{´ØÓ" >>> a=2 >>> eval("a==1") 0 >>> eval("a=1") Traceback (most recent call last): File "", line 1, in ? File "", line 1 a=1 ^ annCharles@tom.com 1102,208 Python ÆS)P §3.2 ÚöŠXڃ'N^ SyntaxError: invalid syntax §3.2 ÚöŠXڃ'N^ ÚXڃ'&EÑ3sys ¥§^import sys¦^" ~X§·-1ëê(command line arguments)"sys.argv´˜‡list§¹¤k ·-1ëê" IOÑ\ÑÑ"sys.stdout§sys.stdin§sys.stderr ©OL«IOÑ\Ñѧ †ØÑÑ©‡é–" òѧS"sys.exit(exit_code)   XÚ ¥ modules§sys.modules´ ˜ ‡dictionary § L«XÚ ¥ ¤ k Œ ^ module §~Xsys.modules["os"] L«module os§Ò´`¦‚•Ó˜‡é–" $1öŠXڂ¸sys.platform sys.path ´˜‡list§²¤kémodule §package ´»" ÚöŠXڃ'N^ÚöŠos ¥§^import os¦^" os.environ ˜ ‡dictionary§  ¹ ‚ ¸ C þ  N  ' X"os.environ["HOME"] Œ±‚¸CþHOME Š" os.chdir(dir) UCc8¹ os.cwd() c8¹ os.getegid() k|id os.getgid() |id os.getuid() ^rid os.geteuid() k^rid os.setegid() ˜k|id os.setgid() ˜|id os.setuid() ˜^rid os.seteuid() ˜k^rid os.getgroups() ^r|¶¡L os.getlogin() ^r¹¶¡ os.getenv ‚¸Cþ os.putenv ˜‚¸Cþ os.umask ˜umask L 3.2-3: XÚN^Þ~ õ §L3.2-3 ==јÜ©"‡UŽXÚN^§3python¥ÑUé" annCharles@tom.com 1103,208 Python ÆS)P n Python ~^¬ e¡kA‡~f" ˜‡{üshell |^os.system() ?˜‡{üshell" #!/usr/bin/python import os,sys cmd=sys.stdin.readline() while cmd: os.system(cmd) cmd=sys.stdin.readline() os.system(cmd)|^XÚN^§$1lIOÑ\Ö5·-" Ä©‡öŠõU |^os ¥Ä©‡öŠõU"k:aqshell§,Ñ\Ø {ö" >>> os.mkdir(’/tmp/xx’) #Mï8¹ >>> os.system("echo ’hello’ > /tmp/xx/a.txt") 0 >>> os.listdir(’/tmp/xx’) >>> os.listdir(’/tmp/xx’) [’a.txt’] >>> os.rename(’/tmp/xx/a.txt’,’/tmp/xx/b.txt’) >>> os.listdir(’/tmp/xx’) [’b.txt’] >>> os.remove(’/tmp/xx/b.txt’) >>> os.listdir(’/tmp/xx’) [] >>> os.rmdir(’/tmp/xx’) >>> os.listdir(’/tmp/xx’) #¤õíØ 8¹ Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 2] No such file or directory: ’/tmp/xx’ „kchown§chmod§unlink§symlink§link"ÙGUnix §ATÙGù öŠ" os ¥„kéõ¼ê§¯¢þ§‡´POSIX IO¼ê±93ŒõêUnix ²2 ¦^¼ê3Python Unix ‡p¡Ñ´|±"ù Ñ´„ÌPOSIX .~"k Ö‰5Advanced Programming In Unix Environments 6éÐ0 Unix e?§" annCharles@tom.com 1104,208 Python ÆS)P §3.2 ÚöŠXڃ'N^ )pipe§dup§open öŠ+§©‡£ãΧ?§§ªà§?Ö§^r§^r| " ^os.path ?²Ã'§S ^os.path ?Õáu²§S"·‚Windows(DOS)§MAC ÚUnix 'u ©‡¶¡§8¹¶¡§´»¶¡^{´ØÓ"˜‡{ü~f´§DOSe·‚ ^C:\temp\a.txt L«˜‡©‡Unix e´/tmp/a.txt"e¡~fŒ±w˜ ^{: >>> os.getcwd() ’/home/Charles’ >>> os.path.split(os.getcwd()) (’/home’, ’Charles’) #^u©m˜‡8¹¶¡¥8¹Ü©Ú©‡¶¡Ü©. >>> print os.path.join(os.getcwd(),os.pardir,’a’,"a.doc") /home/Charles/../backup/a.doc #Úsplitƒ‡,ܤ´»¶¡. #os.pardir L«c²eL«þ˜?8¹iÎ.. >>> print os.path.exists(os.getcwd()) 1 #䩇´Ä3. >>> os.path.expanduser(’~/dir’) ’/home/Charles/dir’ #r ~ *Ф^rŠ8¹. #3 Windows eŒU´ H:\Charles\dir >>> os.path.expandvars(’$TMP’) ’/tmp’ #*Ђ¸Cþ,Windows eŒU´ c:\temp >>> os.path.isfile(os.getcwd()) 0 #´©‡¶íº0, Ø´ >>> os.path.isfile(os.path.expanduser("~/tmp/a.c")) 1 #·8¹e¡k /home/Charles/tmp/a.cù‡©‡ >>> os.path.isdir(os.getcwd()) 1 #´8¹íº 1, ´ >>> os.path.islink(os.getcwd()) 0 annCharles@tom.com 1105,208 Python ÆS)P n Python ~^¬ #´ÎÒëíºWindows eŒUØU^ù‡¼ê >>> os.path.ismount(os.getcwd()) 1 #´©‡XÚSC:íºWindows eŒUØU^ù‡¼ê >>> os.path.samefile(os.getcwd(),’/home/Charles’) 1 #wwü‡©‡¶¡´Ø´Ә‡©‡. >>> def test_find(filename,dirname,names): ... if filename in names: ... print os.path.join(dirname,filename) ... >>> os.path.walk(’/home/Charles’,test_find,"a.c") /home/Charles/tmp/a.c ˜‡~fék¿g§os.path.walk(p,func,arg) 1˜‡ë괘‡8¹¶i§1 ‡ë괘‡¼ê¶i§1n‡ëê‘B´Ÿo"os.path.walk ¬rH{p e¤k f8¹§)p§éuz˜‡8¹§Ñ¬N^func§func(arg,dirname,names) 1˜‡ ëêÒ´§walk ˜‡ëêarg§dirname´–¯8¹¶¡"names ´˜‡list§ ¹dirname8¹e¤kSN"ùþ¡@41§S¿g´§3,‡8¹¥§Ú¦¤ kf8¹¥鶡´a.c ©‡½ö8¹"·´3Unix ‚¸e§Windows eATa q" §3.2.1 ‹m©‡ file 閴˜‡Ústring§integer§float ˜S˜é–a."¦k±e{" f=open("filename","r") filename  ½ © ‡ ¶ ¡ §“r” ^  Ö  ª ‹ m §“w”L«   ª §“rw”L«Ö   ª§“rb”L«Ö?›ª§“wb”L«?›ª" §3.2.2 Ö©‡ openˆ£˜‡file 閧Œ±^˜e{Ö˜‡©‡" >>> f=open("/tmp/x.txt","w") >>> f.write("a") >>> f.close() >>> f=open("/tmp/x.txt","r") >>> f.read() ’a’ >>> f.read() annCharles@tom.com 1106,208 Python ÆS)P §3.3 regular expression ’’ ùã“èk‹m˜‡©‡§, ˜‡iΧ,'4§2^֐ª‹m§ÖÑ5ff ?iÎ"f.read(size)L«l©‡¥Ösize ‡iΧXJÑsize @oòr¤ kSNÖÑ5"XJ ©‡(—§f.read(size) ¬ˆ£˜‡˜iÎG"5¿˜ iÎGL«Ü6b§Œ±^e¡ª˜‡˜‡iÎÖ" f.open("/tmp/x.txt","r") c=f.read(1) while c: print c c=f.read(1) f.readline() Ö˜1§·^u1öŠ"XJ ©‡(—§Òˆ£˜iÎG" f.readlines() Ö©‡¤kSN§ˆ£˜‡list §list ¥z˜‡ƒL«˜1§ ¹“\n”" f.write(str)r˜‡iÎG\©‡¥" f.tell() ˆ£c©‡Ö ˜" f.seek(off,where) ^5½ ©‡Ö ˜"where= 0 L«lmŽå§1L«l c ˜Žå§2L«l(—Žå"offL«£Ä £þ§ꕩ‡(—£Ä§KêL« •©‡mÞ£Ä"5¿sys ¥sys.stdout§sys.stderr §sys.stdin ´n‡›©k^ ©‡é–" >>> import sys >>> a=sys.stdin.readline() Hello #Ñ\˜‡iÎG >>> sys.stdout.write(a) Hello #ÑÑ >>> ÚÖöŠéAöŠ´writeline§write§writelines" §3.2.3 '4©‡ ,Python ¬gÄrvk'4©‡Ñ'K§´²w²'4©‡o´˜‡Ð5 ¿§^ À܇˜¬ §  ä‡P৯Œ‡PM"'M{ ü§f.close()(å" §3.3 regular expression regular expression (KLˆª)§{¡regexp§´?Èn¥˜‡Vg§3Unix ­.¥Ã¤Ø3§vi!emacs!sed!awk!perl Ñ2¦^"python ¥re§´˜ annCharles@tom.com 1107,208 Python ÆS)P n Python ~^¬ ‡regexp module ÏL¦Œ±”perl ¥˜¦^regexp"regexp Ò´˜«L«˜‡iÎ G8Ü(set){"`,‡iÎGÚ,‡regexp š(match¤§¿gÒ´`ù‡iÎG ´regexp ¤Lˆ8Ü¥˜‡ƒ"3Python ¥§match „L«,‡iÎGmÞ˜ Ü©Ú,‡regexp match" §3.3.1 {üregexp {üregexp L«keZiÎ|¤§L«iÎ" >>> p=re.compile("abc") >>> if p.match("abc") : print "match" ... match >>> ù p 0 ˜ ‡ { ü  ^ { § Ä k ‡ ) ¤ ^re.compile("abc") ˜ ‡pattern ( ª)§pattern ˜‡match {§XJÚ,‡iÎGš§Òˆ£˜‡match object§ ÄK҈£None"Ø , AÏiÎmetacharacter (iÎ) §ŒõêiÎÑÚgš" ù AÏiδ " ^$*+?{[]\|() §3.3.2 iÎ8Ü ^[]Œ±L«iÎ8Ü"k±eA«^{ • ÑiΧX[abc] L«ša ½öb ½öc§½ö`i1a§b§c Ñ3[abc]L« 8Ü¥"Œõêmetacharacter 3[] ¥¬”metacharacter AϿ§L« Úš"~X: >>> a=".^$*+?{\\|()" >>> p = re.compile("["+a+"]") >>> for i in a: ... if p.match(i): ... print "[%s] is match"%i ... else: ... print "[%s] is not match"%i ... [.] is match [^] is match [$] is match [*] is match annCharles@tom.com 1108,208 Python ÆS)P §3.3 regular expression [+] is match [?] is match [{] is match [\] is not match [|] is match [(] is match [)] is match Œ„Œõêmetacharacter 3[]¥ÑÚš§´ko‡metacharacter ØÚ š§@Ò´“^[]\”§¡¬˜‡˜‡`²§^ L«‡§¡0 §[]XJÑy 3[]¥§Ò¬©Ø˜Ù=p´mÞ=p´(— "\ Š^´^5L«Ã{^‹< iÎ" • XÛ3[]¥¹[]§L«Ú“[” ½ö“]” š? >>> p=re.compile("[\]\[]") >>> p.match("]") <_sre.SRE_Match object at 0x815de60> >>> p.match("]") <_sre.SRE_Match object at 0x81585e8> >>> p.match("[") <_sre.SRE_Match object at 0x8158330> ^\[ Ú\] L« • ^ Ñy3[]mÞ§L«‡§Ú[]¥iÎÑؚ§vkÑyҚ"[^abc] L«šØ a§b§cƒ ¤kiÎ"^ Ñy3[] ¥m{§Òvkù‡¿g § L«^iÎ"wþ¡~f§^vkÑy3mÞ§ÒÚgš" • Œ±^-L«‰Œ"[a-zA-Z]š?ۘ‡=©i1"[0-9]š?ۘ‡êi" •\ 3[] ¥Ù¦©^" \d [0-9] \D [^0-9] \s [ \t\n\r\f\v] \S [^ \t\n\r\f\v] \w [a-zA-Z0-9_] \W [^a-zA-Z0-9_] \t L«Útab š§Ù¦ÑÚiÎGL«{˜— \x20 L«Ú›8?›ascii 0x20 š k \ §Œ±3[] ¥L«?ÛiÎ"5¿§üÕ˜‡“.”XJvkÑy[]¥§L« Ø †1\n ± š?ÛiÎ"aq[^\n]" annCharles@tom.com 1109,208 Python ÆS)P n Python ~^¬ §3.3.3 ­E Œ±^˜e{L«˜‡regexp ­E" •{m,n} L«Ñ ym ‡ ± þ( ¹m‡)§n‡ ± e( ¹n‡)"Xab{1,3}c Ò ¬ Úabc§abbc§abbbc š§´Ø¬Úac§abbbbc š"m´e.§n´þ."mŒ ±ŽÑ§L«e.´0§nŒ±ŽÑ§L«þ.´ÃŒ" •*L«{,}§vkÑy(0g)§­EÑy1g±þ" • + L«{1,}§­EÑy1g±þ •?L«{0,1}§­EÑy0g½ö1g" Œšځš¯K"Ÿo¬kù‡¯Kºwe¡~f"[ab]* Úababab ?1 š§@o´Úa š„´Úababab šQºXJÚa š§‰š§Úababab š §‰Œš"python ¥Ñ´Œš" >>> re.compile("a*").match(’aaaa’).end() 4 >>> re.compile("a*?").match(’aaaa’).end() 0 match object endŒ±š˜‡iΠ˜"XJ‡š§@oÒ 3*§+§?§{m,n} ¡\˜‡?§C¤*?§+?§??§{m,n}?L«š" §3.3.4 ¦^©iÎG · ‚   § i ÎGL«   { ¥ ^\\ L« i Î\§ 3regexp ¥ Œ þ  ¦ ^\§ ¤ ± 3regexp¥ Ñ y Œ þ\\ù  K  Œ Ö 5 § ‡ 3regexp ¥ š \I ‡ ù  re.compile("\\\\") ù¬éæ†")ûù‡¯K{´µ3iÎGc¡\˜‡r L«raw ‚ª§\Aϊ^Ò؄ "¤±3python L«regexp˜„Ñ^\r{"~ X >>> a=r"\a" >>> print a \a >>> a=r"\"a" >>> print a \"a >>> §3.3.5 ¦^re ¬ ¦^regexp§Ï~^±eA‡Ú½µ annCharles@tom.com 1110,208 Python ÆS)P §3.3 regular expression • k^re.compile ˜‡RegexObject§L«˜‡regexp" • ,^pattern match§search{§MatchObject" • 2^match object š ˜§šiÎG&E" RegxObject ~^¼ê: • RE_obj.match(str,[pos[,endpos]])§ XJstr m ÞÚRE_objš  §   ˜ ‡MatchObject ÄKˆ£None"5¿´lstrmÞm©?1š" >>> re.compile("a").match("abab") <_sre.SRE_Match object at 0x81d43c8> >>> print re.compile("a").match("bbab") None • RE_obj.search(str,[pos[,endpos]])§3str¥|¢1˜‡ÚRE_objšÜ©" >>> re.compile("a").search("abab") <_sre.SRE_Match object at 0x81d43c8> >>> print re.compile("a").search("bbab") <_sre.SRE_Match object at 0x8184e18> 5¿Úmatch()ØÓ"Ø7lmÞҚ" • RE_obj.findall(str)§ˆ£str¥|¢¤kÚRE_objšÜ©"ˆ£˜‡tuple§ Ù¥ƒ´šiÎG" MatchObject~^¼ê • m.start() ˆ£å© ˜§éuRE_obj.match()ˆ£MatchObject§start()o´ ˆ£0 • m.end() ˆ£(堘(؝¹T ˜iÎ)" >>> s="I say:helloworld" >>> m=re.compile("hello").search(s) >>> for i in range(m.start(),m.end()): ... print s[i] ... h e l l o >>> annCharles@tom.com 1111,208 Python ÆS)P n Python ~^¬ • m.span() ˆ£˜‡tuple L«(m.start(),m.end())" • m.pos()§m.endpos()§m.re()§m.string() § ù © OL«) ¤ ù ‡MatchObject¼ê¥ëê" RE_obj.match(str,[pos[,endpos]]),RE_obj.search(str,[pos[,endpos]]) ¥pos§endpos§RE_obj§str"Ò´` m.re().search(m.string(),m.pos(),m.endpos()) ¬m" • m.finditer() Œ±ˆ£˜‡iterator§^5H{¤kéMatchObject" >>> for m in re.compile("[ab]").finditer("tatbxaxb"): ... print m.span() ... (1, 2) (3, 4) (5, 6) (7, 8) §3.3.6 p?regexp Ø c¡0 §„kéõk^Lˆregexp ª" • | L«éÜõ‡regexp "XJAÚB ´ü‡regexp §@oA|B L«ÚA š½öÚB š"´5¿| OŽ`k?$§Good|Bad ¬Ú“Good” ½ö“Bad” š§Ø ¬Ú“Goodad” ½ö“GooBad”š" • ^ L«š˜1m©1Ä"~X“^abc”¬Ú“abc”š§´Ø¬š“xabc”§c Ù´^search žÿ"^ 3mÞâkù«AϿ§Ҵ´`§k3mÞ§^â ´metacharacter §ÄK^ Ò´˜‡ÊÏiÎ" • $ L«š˜1(—"Ú^ aq§k3˜‡iΞÿ§$ âkù«AÏ¿ g" •\A L«šiÎGmÞ"XJvk3õ1ª(MULTILINE) ežÿ§\A Ú^ ´˜‡¿g§´3õ1ªe\A š1˜11Ä" ^šz˜11Ä" •\Z L«šiÎG(—"XJvk3õ1ª(MULTILINE) ežÿ§\Z Ú$ ´˜‡¿g§´3õ1ªe\Z š˜11—" ^šz˜11—" •\b šc>.§3NJ¥§c>.´éJ.½§´3=Š¥I:ÎÒ§˜ ‚ь±L«˜‡üc>.§Ù¦Šókaq§äNXÛ.½§dlocale û ½"~X\binfo\b ¬š“info” جš“information”"´‡5¿e¡~ f" annCharles@tom.com 1112,208 Python ÆS)P §3.3 regular expression >>> print re.compile(r"\binfo\b").match("info ") #¦^ raw ‚ª <_sre.SRE_Match object at 0x817aa98> #\b L«üc>. >>> print re.compile("\binfo\b").match("info ") #vk¦^ raw ‚ª None #\b L«ò‚ÎÒ >>> print re.compile("\binfo\b").match("\binfo\b ") <_sre.SRE_Match object at 0x8174948> 5¿VÚÒc¡r"3vk´^raw ‚ªžÿ§\bL«ò‚ÎÒ§0x8§¦^raw ‚ªžÿ\bL«üc>." •\B L«ššüc>." ±þ¤kmetacharacter ¿ØÚýiΚ§´˜«^‡u§Ø¬¦^š Ü©O\Ý"~X: ^abc š“abc”§´š݄´3"1 §3.3.7 ©|(Group) Ï~œ¹§\ýŽ‡´šiÎG¥˜Ü©§ Ø´Ü"regexp ²~^ 5r˜‡iÎG©)¤A‡Ü©§ù~féõ§Xemail ¥©)email header(&Þ) Úemail body (©)§email header ¥q‡©)u&<§Â&<§email /Œ¥q‡© )^r¶¡§Ú^r¶"~X§\^e¡‚ª;˜‡Ï&¹" name: Charles Address: BUPT telephone: 62281234 email: annCharles@tom.com name: Ann Address: BUPT telephone: 62284321 email: CharlesWang@peoplemail.com.cn ^˜1©mP¹"@҇Charles §Ann ¶¡Ü©§BUPT /ŒÜ©"XÛ) ûù‡¯KQ? Group ! we¡~f" >>> x=""" ... name: Charles ... Address: BUPT ... telephone: 62281234 ... email: annCharles@tom.com ... 13lex ¥§“ˆabc” šÝ'“abc” Œ annCharles@tom.com 1113,208 Python ÆS)P n Python ~^¬ ... name: Ann ... Address: BUPT ... telephone: 62284321 ... email: CharlesWang@peoplemail.com.cn ... """ >>> p=re.compile( ... r"^name:(.*)\n^Address:(.*)\n^telephone:(.*)\n^email:(.*)\n",re.M) >>> for m in p.finditer(x): ... print "here is your friends list" ... print "%s,%s,%s,%s"%m.groups() ... here is your friends list Charles, BUPT, 62281234, annCharles@tom.com here is your friends list Ann, BUPT, 62284321, CharlesWang@peoplemail.com.cn ù‡~fk:E,§´ATvkŸoŠ{¡¯K§õꜹŒ±Ãþ)û¯K" '…3p.compile()?§Ù¥(.*)¥õ ˜‡)Ò§L«group§Ò´L«š˜Ü ©"3MatchObject ¥groups() ˆ£¤kšgroup§~f¥©OL«Charles  "MatchObject ¥start() !end()!span() !group() ь±D4ëê§L«group Òè§0o´3§ …´"Žëê§L«šoiÎG"l1 m©O꧘ †regexp ¥Œgroup ꧤ±§~f¥m.start(1)L«name §m.start(2) L «Address ")Ò´Œ±i@§ùžOŽgroup Òè§Òêê(  ˜§~X: >>> re.compile("(a(b)c)d").match("abcd").groups() (’abc’, ’b’) >>> kü|)Ò§êê(  ˜§k´abc §,´b"p.finditer(x) 3c¡0 L§Œ±^ 5H{¤kéMatchObject"¡print Šé^m.groups() 5‚ªz˜‡iÎG" Ϗm.groups() ´˜‡tuple§Ù¥z˜‡ƒ´˜‡string"group Ø ù«^{§„ Œ±L«O†§X:(\b\w+)\s+\1 ÒL«šëYÑyü‡Óüc" lþ¡~f¥§¬wkù˜‡¯K§^m.group(1) L«name§éؘ٧ …XJ3 O\˜‡group {§ÒI‡N¡¤kgroup Òè"XJU ^m.group(’name’) 5L«name {§@oҘßõ "ù‡¯K´ù)û§w e¡~f: >>> p=re.compile(r"^name:(?P.*)\n^Address:(?P
.*)\n" \ r"^telephone:(?P.*)\n^email:(?P.*)\n",re.M) >>> for m in p.finditer(x): annCharles@tom.com 1114,208 Python ÆS)P §3.3 regular expression ... print m.groups() (’ Charles’, ’ BUPT’, ’ 62281234’, ’ annCharles@tom.com’) (’ Ann’, ’ BUPT’, ’ 62284321’, ’ CharlesWang@peoplemail.com.cn’) >>> matchs=[m for m in p.finditer(x)] >>> matchs[0].group(’name’) ’ Charles’ >>> matchs[0].group(’address’) ’ BUPT’ >>> matchs[0].group(’telephone’) ’ 62281234’ >>> matchs[0].group(’email’) ’ annCharles@tom.com’ >>> matchs[1].group(’name’) ’ Ann’ >>> matchs[1].group(’address’) ’ BUPT’ >>> matchs[1].group(’telephone’) ’ 62284321’ >>> matchs[1].group(’address’) ’ BUPT’ >>> matchs[1].group(’email’) ’ CharlesWang@peoplemail.com.cn’ 3ù‡~f¥§^(?P.*) “O (.*)§ÒŒ±^m.group(’xxx’)¢Úšgroup § Ø´^group Òè §3éE,regexp žÿ§wAOk^"ù«{ ´python gC*ЧÚÙ¦{ØoN§f`Perl 5 Jø aqś§´  ±•oNPython „´3 ù«*Ð"3L«O†žÿ§Ò^(?=) 5¿vk regexp Ü©"X:(\b\w+)\s+\1 ÒL«šëYÑyü‡Óüc"Œ±U¤ §(?P\b\w+)\s+(?=)§´˜‡¿g"„k˜«Y§·Üu®²^group Òè §´ŽO\˜‡group ´q؎K5Òè^S"⊉Non-capture group" O\ ˜‡group§´Ø¦©Ò觴vk{3MatchObject ù‡group  šÜ© "^(?:...)5L«˜‡Non-capture group"Ù¥:L«ù«)ûY*А {"ùØ´‡Ð{" §3.3.8 Compile Flag 3^re.compile RegxObject žÿ§Œ±k˜ flag ^5NRegxObject  [A" annCharles@tom.com 1115,208 Python ÆS)P n Python ~^¬ DOTALL§S 4. š?¿iם)†1Î\n IGNORECASE§I ь LOCALES§L 4\w!\W!\b!\B Úclocale˜— MULTILINE§M õ1ª§K^Ú$ VERBOSE§X verbose ª §3.4 ^struct¬?n?›êâ C Šó§S ŒUkù²{§½Â˜‡struct §,†^e¡ª?n" struct{ ... } header; write(fd,(void*) &header,sizeof(struct)); read(fd,(void*) &header,sizeof(struct)); 3Ö?›©‡§X(ѧ㡧㔧¦‚˜„Ñk˜‡©‡Þ‚ª"ù«{4 ·^"„k3?näÏ&§Sžÿ§´ék^"Python kaq?n{" …é{ük§‡struct ¬¥pack§unpack§Úcacsize Òt½ "¦^ù‡ ¬žÿ§õI‡éC Šók )"w‡~f: $cat a.c #include struct testheader{ int version; char tag[4]; }; struct testheader header={0x00010002,"WAVE"}; int main(int argc, char **argv) { FILE * fp = fopen("test.dat","wb"); if(!fp) return 1; fwrite((void*)&header,1,sizeof(header),fp); fclose(fp); return 0; } $gcc -o x a.c $./x $xxd test.dat 0000000: 0200 0100 5741 5645 ....WAVE annCharles@tom.com 1116,208 Python ÆS)P §3.4 ^struct¬?n?›ê⠘‡C §S§ ˜‡©‡Þ"¹‡&Eژ‡iÎ~þ"xxd Œ±w«?›© ‡"little endian ‚ª" >>> import struct >>> data = open(’test.dat’,’rb’).read() >>> start,stop = 0 , struct.calcsize(’hh4s’) >>> ver1,ver2,tag= struct.unpack(’hh4s’,data[start:stop]) >>> ver 2 >>> subver 1 >>> tag ’WAVE’ ù‡~f¥§Œ±?›©‡Þ&E"unpack 1˜‡ëê^u£ãstruct ( §1‡ëê´Ñ\?›êâ" ‚ª½ÂXL3.4-4"L3.4-4kA‡Š5¿/" ‚ª C Šóa. Python a. x char Ã(L«W¿i!) c char ݏ1iÎG b signed char Integer B unsigned char Integer h signed short Integer H unsigned short Integer i signed int Integer I unsigned int Integer l signed long Integer L unsigned long Integer q signed long Integer Q unsigned long Integer f float Float d double Float s char[] String p char[] String P void* Integer L 3.4-4: struct ¬¥‚ª½Â annCharles@tom.com 1117,208 Python ÆS)P n Python ~^¬ iÎ i!^S ÝÚéàª @ native native = native standard < little-endian standard > big-endian standard ! network (= big-endian) standard L 3.4-5: i!^S½Â • q§Q k3Åì|±64  öŠžÿâk¿Â" • z‡‚ªc¡Œ±k˜‡êi§L«õ‡"Xþ¡~f¥Œ±¤" >>> struct.unpack(’2h4s’,data[start:stop]) (2, 1, ’WAVE’) • x L«W¿ §vkÑÑ(J"X >>> struct.unpack(’xxh4s’,data[start:stop]) (1, ’WAVE’) • s ‚ªÒ´L«˜½ÝiÎG§4sL«ݏ4iÎG"´p ØÓ§¦L «“Pascal String”§?›ê⥧ ˜‡i!L«iÎGݧŒ256§¡â´ TÝiÎG" •P ^ÚÅìƒ'ݧ=†˜‡"64  Åì^long integer§32  ^integer" 3"Žœ¹e§struct ¬Šâ/Åìi!^S=†§Ò´`§Intel CPU ^little-endian§SPARC  CPU ^big-endian"i!éàªÚ/C Šó?Èì¥ éàª´˜—"„Œ±^‚ª¥1˜‡iÎ5UCù«ª§XeL3.4-5: ~X: >>> data ’\x02\x00\x01\x00WAVE’ >>> struct.unpack(’!hh4s’,data) (512, 256, ’WAVE’) >>> struct.unpack(’] say hello to somebody """ say_hello ÒC ¤ Documented commands. Ñ\“ help say hello” Ò ¬ ‰ 1help_say_hello" XJ·‚½Â: def help_test(self): print """ this is only a test topic """ “test” Ò¤Miscellaneous help topics"Œ±Ñ\“help test” ‰1help_test Œ±ÏL“?test” “?say hello” ˜J" annCharles@tom.com 1122,208 Python ÆS)P §3.5 ^Cmd ¬?{ü·-1 §3.5.9 $1Shell õU ·‚½Â: def do_shell(self,argc): import os os.system(arg) Œ±Ñ\“shell ls” ½ö“!ls”§‰1shell ¤ ¼ê" §3.5.10 getattr õU¦^ getattr ¼ê¦^§´Cmd ¬¥'…Eâ" ·‚˜„·-1)º§S§Ñ´‡‰˜‡L§^5éAz˜‡·-§ÚƒA ·-?n¼ê§´Cmd ¬¥§‡½Â·-?n¼êҌ± §´No¢yQº def onecmd(self, line): # line ´^rÑ\·-1" # r line ©)¤·-Ü©ÚëêÜ©" cmd, arg, line = self.parseline(line) try: # ± do_cmd ‚ªmÞ¼êé–" func = getattr(self, ’do_’ + cmd) except AttributeError: return self.default(line) #N^ func é–" return func(arg) dþ¡˜ã“觌±wgetattr ¦^´'…"ù«A5¦§SŒ±Ä é–¤k¤ " ù 㠓 è k ˜ ‡   ¯ K § Ò ´ v k é   func Š u  § XJU  äcallable(func) Ò¬Ð§Ø,§fa½Âdo_cmd ´¤ ¼ê§ ´¤ C þ§@oÒ¬)É~" Ó§Ï&E)¤§¦Îhelp_cmd ‚ª¤ ¼ê" Ï©a´Úgetattr k'X" • Undocumented commands: kdo_cmd ‚ª¤ ¼ê§´vkhelp_cmd ‚ª¤ ¼ê" • Documented commands: kdo_cmd ‚ª¤ ¼ê§khelp_cmd ‚ª¤ ¼ê" annCharles@tom.com 1123,208 Python ÆS)P n Python ~^¬ • Miscellaneous help topics: vkdo_cmd ‚ª¤ ¼ê§´khelp_cmd ‚ª¤ ¼ê" ù§§SžÿØI‡ˆ«a.Ï¼ê‰©a§§SÒJø v & E§^u©a" §3.6 ?n·-1À‘ ÙGUnix <ѧUnix ekéõ·-Ñ´Œ±?néõéõ·-1À‘§^u› ›§S1§Ú²§S‡?n©‡¶¡"X: ls -l -a grep -i a somefile getopt Ò ´  B § S ? n ·- 1 ë ê  ˜ ‡module "getopt.py 3/usr/lib/python2.2/ e §3.6.1 ˜‡{ü~f “èdemo_getopt.py #\ getopt from getopt import * import sys opts,args = getopts(sys.argv[1:],"a","--all") print opts print args $1(J: %python demo_getopt.py -a f [(’-a’, ’’)] [’f’] %python demo_getopt.py [] [] %python demo_getopt.py --all [(’--all’, ’’)] [] %python demo_getopt.py -x Traceback (most recent call last): File "demo_getopt.py", line 4, in ? annCharles@tom.com 1124,208 Python ÆS)P §3.6 ?n·-1À‘ opts,args = getopt(sys.argv[1:],"a","all") File "/usr/local/lib/python2.3/getopt.py", line 91, in getopt opts, args = do_shorts(opts, args[0][1:], shortopts,args[1:]) File "/usr/local/lib/python2.3/getopt.py", line 191, in do_shorts if short_has_arg(opt, shortopts): File "/usr/local/lib/python2.3/getopt.py", line 207, in short_has_arg raise GetoptError(’option -%s not recognized’ % opt, opt) getopt.GetoptError: option -x not recognized lþ¡~fŒ±wѧgetopt I‡k3 ‡ëêÑ\" • sys.argv[1:] ‡)º·-1À‘"؝)·-" •"a" áÀ‘ áÀ‘´^˜‡“-” ©…À‘¶¡§Ò–ls -a ¥a ˜"^˜‡i1L«" •["all"] L«À‘" XJk˜‡À‘§@o҆¤˜‡iÎG§XJؐ˜‡À‘§@o҇ ¤iÎGlist" ÃØáÀ‘§Ñ؝)c¡“-” ½ö“–”" getopt ˆ £ ˜ ‡tuple§ ¹ k ü ‡  ƒ §opts,args§args L« v k ) º L sys.argv[1:] Ü©§˜„L«I‡?n©‡¶¡" opts L«uyÀ‘§´˜‡list§list ¥z˜‡ƒ´˜‡tuple§L«˜‡pair, (opt,val)§opt L«3·-1¥uyÀ‘¶¡"val L«À‘¤éAëê"XJ´ ˜iÎG§L«TÀ‘vkëê"opts ¥À‘Ñy^SÚ·-1þÑy^S´˜ "#NÀ‘­EÑyõg" XJ3·-1þuyØU)ºëê§KÑGetoptError É~"GetoptError ¥ msgá5L«Ñ†£ã§optá5L«ØU)ºÀ‘" §3.6.2 ‘këê·-1À‘ éuáÀ‘§3À‘¡‹˜‡kÒL«ù‡À‘I‡ëê"~Xµþ‡˜‡~f¥ getopt U" getopt(sys.argv[1:],"a:","all") XJ·-1¥vkJøÀ‘§˜¬ÑGetoptErrorÉ~"$1(J: annCharles@tom.com 1125,208 Python ÆS)P n Python ~^¬ %python demo_getopt.py -a Traceback (most recent call last): File "demo_getopt.py", line 4, in ? opts,args = getopt(sys.argv[1:],"a:","all") File "/usr/local/lib/python2.3/getopt.py", line 91, in getopt opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) File "/usr/local/lib/python2.3/getopt.py", line 195, in do_shorts opt) getopt.GetoptError: option -a requires argument %python demo_getopt.py -a b [(’-a’, ’b’)] [] éuÀ‘§K‡3À‘¶¡¡\˜‡Ò"~X: getopt(sys.argv[1:],"a:","all=") (J´: %python demo_getopt.py -a b --all xx file1 file2 [(’-a’, ’b’), (’--all’, ’xx’)] [’file1’, ’file2’] §3.6.3 optparser ¬ optparser ¬´Python 2.3 ‘˜‡rŒ!(¹!´^!´*з-1)ºì"¦ ^optparser ¬§^é“è§ÒŒ±\§SO\61§;’·-1" ¦'getopt ¬Ð^" ùpk˜‡{ü~f #!/usr/bin/env python # simplyOptparser1.py from optparse import OptionParser parser = OptionParser(version="%prog 0.1 ") parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don’t print status messages to stdout") annCharles@tom.com 1126,208 Python ÆS)P §3.6 ?n·-1À‘ (options, args) = parser.parse_args() D = vars(options) for i in D: print i,"=",D[i] ù§\§SҔ¤kGNU eó䘧kéõoption Œ±¦^" %./simplyOptparser1.py -f output --quiet verbose = False filename = output %./simplyOptparser1.py -qf output verbose = False filename = output %./simplyOptparser1.py -q --file=output verbose = False filename = output %./simplyOptparser1.py --quiet --file=output verbose = False filename = output %./simplyOptparser1.py --help usage: simplyOptparser1.py [options] options: --version show program’s version number and exit -h, --help show this help message and exit -fFILE, --file=FILE write report to FILE -q, --quiet don’t print status messages to stdout %./simplyOptparser1.py --version simplyOptparser1.py 0.1 % §Swå5é;’" optparser Ong optparser ¬Ong錧ÝþÉ Unix ÚGNU eóä8K"y0 ˜ âŠ: • argument (·-1ëê) annCharles@tom.com 1127,208 Python ÆS)P n Python ~^¬ %ls -l /usr Ù ¥-l usr Ò ´ ·- 1 ë ê "sys.argv ´ ˜ ‡list § ^ u L«·- 1 " ~ f ¥§sys.argv Ò´ [’ls’,’-l’,’/usr’] ·-1ëêÒ´sys.argv[1:] §Ïsys.argv[0] L«·-" • option (·-1À‘) §S3‰1žÿ§largument &E§^5N§S‰1"DÚUnix ÚGNU ·-1Š{´: -q -f --file --quiet ˜‡~Ò§¡‹˜‡áÀ‘§½öü‡~Ò§¡‹˜‡À‘"õ‡áÀ‘Œ± Ü¿3˜å§X-qf optionparser Ø|±e¡Š{" • ˜‡~Ò¡‹‡Lü‡iαþáÀ‘§X-pf§ÄKҩؘٴ-p -f ü ‡À‘§„´-pf ˜‡À‘" • ˜‡~Ò¡‹˜‡À‘§X-file §‹þ¡aq§Òvk{©˜Ù -file ´˜‡À‘„´-f -i -l -e o‡À‘º • ^\Ò§“O~Ò§X+f §+rgb §ØÜS." • ^m“O~Ò§~X/l §/rgb §ù´Windows ÚVMS ^{§´3Unix emL«8¹§¤±ls /l— ҩؘٴ/l ´À‘§„´8¹¶¡ " • option augument(À‘ëê) ”-f outputfile ùÀ‘§¡‹˜‡ëê§outputfile §L«À‘ë ê"-foutputfile Ú-f outputfile ј"kÀ‘ØI‡ëê§kÀ‘7 L‰Ñëê" ´ÄI‡optional option argument (ŒÀÀ‘ëê)QºÒ´`§XJ¡‹ ë êÒ@¦´À‘ëê§XJvk§Ò@À‘vkëê"~X§bX-a À‘¡ koptional option argument: ls -a xxx -b L«-a ‘këêxxx § |ls -a -b| L«-a vkëê"´§XJ´ls -ab @o·‚TNo@Qº©Ø˜Ù §¤ ±optionparser ¬Ø|±optional option argument " annCharles@tom.com 1128,208 Python ÆS)P §3.6 ?n·-1À‘ • positional argument ( ˜ëê) 3·-1ëê¥§Ø À‘± §eÒ´positional argument §˜„^uL«© ‡¶¡"~Xµ ls -l /usr /lib Ù¥¥[’/usr’, ’/lib’] Ò´positional argument " • required option (7À‘) ´^r7LJøÀ‘"ù´‡€Ì¿"XJ\§S‡¦^r7LJø˜ option §@où´˜‡éØНO§ék^r¬F%Ñ\¤k\ ‡option ",\XJ˜½‡ùo‰§´q{" ~f: ·-1 µprog -v --report /tmp/report.txt foo bar ·-¶¡: prog argument ·-1ëê: -v --report /tmp/report.txt foo bar option : -v --report option argument : /tmp/report.txt positional argument : foo bar O·-1R¯ • ‡¦^rJø7LJø&EÐ"XJvkoption §§SŒ±~$ 1"ŒõêUnix ÚGNU óäÑ´ù"Ø find, tar, dd §éõ<1µù §S·-1ØIO§N´Úå· " • ؇k7À‘required option "XJ^r7LJøù &E§@o¦‚ÒØ´Œk ŒÃÀ‘ § ´positional argument " • z‡option ÑATkÜn%@Š" • áoption ƒpܧ˜˜éA"á´upªÑ\B§Œ±Jp §S ŒÖ5"¤±§pªshell ¥§Ñ\ls -l 'Ð"´31?n §S ¥§Ð¤--long " ~X: cp ·- cp SOURCE DEST cp SOURCE ... DESTDIR \Ø^?ÛÀ‘§cp oU¤¦̇?Ö§r˜‡©‡€¤,˜‡©‡§½ör˜ 橇€˜‡8¹¥",§\Œ±½éõÀ‘§^u½´Ä3©‡ §´Ä3?Užm§´Ä‹‘ó§´Ä48€8¹§´¦‚ÑØKcp  $1" annCharles@tom.com 1129,208 Python ÆS)P n Python ~^¬ positional argument ˜„´§S7I&E",§k éõ§SØI‡?Û&E§ Œ±éÐ$1§~Xcat, sort, cut, grep, sed, awk, head, tail, ed, uniq, fold, wc, fmt,split, od, xxd, sum, §¦‚ÑÂpositional argument ¥ëꊏÑ\©‡¶¡§´ XJvk½Ñ\©‡¶¡§@oÒlIOÑ\Ö"ù·-š~ЧÚ+śÜ å5§%åá" k §S§K7L‡‰Ñù &E§Xdiff, join, tr, Ϗù §S" 7&E§ÒØU¤§?Ö"X: diff 7L‡‰Ñü‡©‡¶¡§ÄK¦'Ÿo Q? join ´rü‡©‡Ü¿§¤±7L‰Ñü‡©‡¶¡"tr ´€ÈõU§7L`²rŸo €È¤Ÿo§¦âUóŠ"¤±ù 7ëêъpositional argument" cut 3ù˜:þ‰ØЧ %cut cut: you must specify a list of bytes, characters, or fields Try ‘cut --help’ for more information. ù´˜‡~ §cut ˜½‡^rJø&E§NJÑlÑ\¥JÑeZ"^rkõ« ÀJ§²Ui!byte§iÎcharacter „´iãfield ÀJ˜Ü©"·@ATk˜‡%@ Ċcut -f 1 §NùØ´éИ‡ÀJ§½ö%@Ċ´cut -b1 §cut -c1 §´ 䢧oƒATJø˜‡%@Ċ§Oú ^r%§O4^r”F%" b§\§S‡¦^rJø17 ØÓ&E§§SâU¤õóŠ§ÃØ\JøŸ o.¡§´command line, GUI ј§@oAvk>> import socket >>> socket.gethostname() ’charles.home.com.cn’ >>> socket.gethostbyname(socket.gethostname()) ’192.168.200.18’ >>> socket.gethostbyname_ex("www.sohu.com") (’pagegrp1.sohu.com’, [’www.sohu.com’], [’61.135.150.67’, ’61.135.150.69’, ’61.135.150.74’, ’61.135.150.75’, ’61.135.131.73’, ’61.135.131.180’, ’61.135.131.183’, ’61.135.132.172’, ’61.135.132.173’, ’61.135.132.174’, ’61.135.132.176’, ’61.135.133.109’, ’61.135.145.47’, ’61.135.150.65’, ’61.135.150.66’]) >>> socket.gethostbyname("www.sohu.com") annCharles@tom.com 1143,208 Python ÆS)P n Python ~^¬ ’61.135.131.180’ >>> socket.gethostbyaddr("127.0.0.1") (’localhost.localdomain’, [’localhost’], [’127.0.0.1’]) >>> socket.getservbyname("http",’tcp’) 80 >>> socket.getservbyname("mail",’tcp’) 25 >>> socket.getservbyname("smtp",’tcp’) 25 >>> socket.getservbyname("pop3",’tcp’) 110 >>> socket.getservbyname("ftp",’tcp’) 21 >>> socket.getservbyname("tftp",’udp’) 69 >>> socket.getservbyname("time",’udp’) 37 >>> socket.getprotobyname("udp") 17 >>> socket.getprotobyname("tcp") 6 >>> socket.getprotobyname("icmp") 1 >>> socket.getprotobyname("sctp") 132 gethostname Œ±cÌŶ¡" gethostbynameŒ±ŠâÌŶ¡ÌÅIP /Œ" gethostbyname_ex Œ±ŠâÌŶ¡ÌŤk¶¡&E"¦ˆ£˜‡tuple" (hostname,hostnamealiaselist,ipaddrlist) ¹kÌŶ¡§ÌÅO¶L§˜‡ÌŌUkõ‡O¶§ÌÅIP /ŒL§˜‡ÌÅ Œ±kõ‡IP /Œ" gethostbyaddr Œ±ŠâIP /ŒÌŤk¶¡&E" getservbyname Œ±ŠâÑÖ¶¡§éAàÒ"I‡½´TCP Ƅ ´UDP Æ" annCharles@tom.com 1144,208 Python ÆS)P §3.8 socket ?§ ¼ê¶¡ ŠÂ htons(sint ) rá.lÌÅ^SCä^S ntohs(sint ) rá.lä^SCÌÅ^S htonl(lint ) r.lÌÅ^SCä^S ntohl(lint ) r.lä^SCÌÅ^S L 3.8-8: ^u=†i!^S¼ê getprotobyname Œ±Šâƶ¡§éAÆÒè§ù‡ŠŒ±D4‰M ïsocket ž socket(domain,type,protocol) ¥11n‡ëêprotocol " e¡¼ê^u=†i!^S"XL3.8-8" Ù¥§h “LÌŧn “Lä§to “L=†§s “Lá.§l “L." §3.8.9 TCP ÚUDP «O TCP ´¡•ë"UPD ´¡•šë"TCP Ҕ‹>{§Ï&ƒck‡ïáë §X§ÁŧÃÒ§$§éf"Ï&.ƒ‡ämë"UDP ҔM&§Ï& ƒcØ^ïáë§r#3&µ¥§3&µþÐ/Œ†uxҌ± " 'XL3.8-9: TCP ¬yÂu^S´˜—§UDP Kج§uàêâkŒUuk–" TCP ¬yØ¬¿”§XJsend ¤õˆ£§@oҘ½ˆ éä…À« S§é‡N^recv Ҙ½¬uàuxêâ"UDP Òج§˜„œ¹e§sendto ²~ÑU¤õ§´Øy鐘½¬Â§kÏLþÆy "˜„{Ò´ z˜‡uxêâ?Ò§éÂÒ£x˜‡A§`·Â §XJ3˜½žmT Svk鐏A§Ò­#ux§­#uxN gƒ§„´”}§K@ux”}"T Ò´‡žžm§˜„´N ¼ê§N OŒ OŒ§ …„‡O\˜‡‘Å £þ§“ Žõ‡ÌÅӞ•Ó˜‡ÌÅux" TCP yuxêâÚÂêâجk­E§UDP Òج§uàêâŒU¬˜ uõ–"ù´ÏUDP ê❲Lõ‡´d샧êâ3ä¥)­E" 3TCP ¥§˜½kClient ÚServer ƒ©§ÏServer ‡ïᘇAÏsocket ^ui fÚÂclient 랦§ˆ£˜‡^uÂuêâsocket ƒ§Client ÚServer 3´é Âu¢N"3UDP ¥§vkServer ÚClient ƒ©§¤kÌÅïá socket ƒ§Ò Œ±Âuê⠧Ә‡socket Œ±^5ÂØÓÌÅUDP êâ§Ó˜‡socket Œ± ‰ØÓÌÅuxêâ" annCharles@tom.com 1145,208 Python ÆS)P n Python ~^¬ TCP UDP Ï&ƒc´Äïáë ´ Ä ´Äy^S ´ Ä ´Äyج ¿” ´ Ä ´Äyج­ E ´ Ä Ï&ª Client/Server 顪 XJÑÖ ì n‡  r ÑÖ § ÑÖ ì à socket êþ n + 1 1 ´Äk6þ›› ´ Ä Âuêâ¦^¼ê send/recv sendto/recvfrom ´Ä¦^listen,accept ´ Ä ¢ž5  Ð L 3.8-9: TCP ÚUDP «O 6þ››¿gÒ´`§XJÂàä…À«÷ §ÒwŠé§éÒ¬ú:u xêâ§XJ˜ §Ò¬wŠéŒ±¯:uxêâ"TCP Œ±§´UDP vkù«Å ›"TCP 3Ï&L§¥§z˜‡Ñk˜‡SÒ§z˜Ñ£Âé(@â@u x¤õ" §3.8.10 'uTCP ÑÖì{K ÑÖìà„É^r랦§„‡?nÂuê⧘„k±e{" 1. ÑÖìfork ˜‡f?§§3f?§¥?nÚéÏ&"I?§UY?nÙ¦^r 랦" 2. ÑÖìM‚§§^ÕႧ?nÚéÏ&" 3. ÑÖì^select ¼ê§ÓÎsocket §Ò´`§3Âuêâƒc§kwwsocket ´Ø ´Œ±Âuêâ" 4. ¦^š{l¼ê§Ò´`§accept send ¼ê¬á=ˆ£" e¡~f§Ñ´¢y˜‡{üÑÖì§Ò´l^r=pÂêâ§,uÂê âH¬‰^r" annCharles@tom.com 1146,208 Python ÆS)P §3.8 socket ?§ Õá?§ ~f: #/usr/bin/env python # echo.server.fork.py # simpleserver.py import socket,sys,os clients=[] def handledata(s): data = s.recv(1024) while data: try: s.send(data) data = s.recv(1024) except: sys.exit(0) def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),8080)) s.listen(10) while 1: clientsocket,clientaddress = s.accept(); pid = os.fork() if pid==0: # child process # close the server socket . # because the child process should not # care about the accept the connect request s.close() handledata(clientsocket) else: # this is parent process # close the client socket # because the parent should not # care about sending/receiving data clientsocket.close() if __name__ == "__main__" : main() annCharles@tom.com 1147,208 Python ÆS)P n Python ~^¬ ~f¥§ÑÖì^r랦§Éë§)˜‡f?§"fork ¼ê¬˜gN^ ügˆ£"ùž§ü‡AÓ?§3S¥$1"ØӃ?3u§f?§ˆ£pid ´0 §I?§ˆ£´f?§ID " f?§ØI‡3?n랦§¤±'4s " ?nÂuêâ" I?§ØI‡?nÂuê⧤±'4clientsocket § UYaccept e˜‡^r 랦" Ÿo‡'4socket §ÏIf?§A˜§¦‚Ó‹msocket "¤±  ;À⧁Ð'4˜ Ø^"f?§'4s §Ø^ú%§sÙ¢„vkýíØ K§Ï„kI?§3^" f?§XJÉ~òÑ §Ø¬KI?§$1"If?§ƒmØ2ê⧦‚ƒ m^Ï&{§Ò7L¦^Ù§?§mÏ&{" ÕႧ ~f: #/usr/bin/env python # echo.server.thread.py import socket,sys,os,thread clients=[] def handledata(s): global clients data = s.recv(1024) while data: try: for i in clients: i.send(data) data = s.recv(1024) except: sys.exit(0) def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),8080)) s.listen(10) while 1: clientsocket,clientaddress = s.accept(); clients.append(clientsocket) annCharles@tom.com 1148,208 Python ÆS)P §3.8 socket ?§ thread.start_new_thread(handledata,(clientsocket,)) if __name__ == "__main__": main() éN´O\˜‡*ÐõU§ÑÖìؐr^ruêâH£§ ´H£‰¤kë ^r§Ò”3m¬˜" ^‚§ª§k˜‡?§3§z˜‡?§Ó˜‡S˜m§¤±é^N´¢ yØÓ?§ƒmÏ&§ÓžéN´)–¯Àâ§I‡c[O§O\&Òþ? n"þ¡~f¥§k˜‡¯K§Ì‚§3V\˜‡socket clients ¥žÿ§¤k f‚§Ñ3ŒU¦^clients §kŒUÀâ" …§?ۘ‡‚§N^ sys.exit ½ö)É~{§@o‡ÑÖìÒK " ¡Ù¦{˜§Ï¦‚Ñ´^˜‡‚§?n" ÓÎ #/usr/bin/env python # echo.server.select.py import socket,sys,os,select clients=[] def handledata(s): data = s.recv(1024) for i in clients: i.send(data) def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),8080)) s.listen(10) while 1: rlist , wlist,xlist = select.select([s,],[],[],0) if rlist: # ok, now a new client comming clientsocket,clientaddress = s.accept(); clients.append(clientsocket) rlist , wlist,xlist = select.select(clients,[],[],0) if rlist: for i in rlist: handledata(i) if __name__ == "__main__": main() annCharles@tom.com 1149,208 Python ÆS)P n Python ~^¬ ù‡~f¥§'…3uselect ¼ê^{§¦^ýÿ´˜|閴ȱÖ"Ñ\ d4‡ëꧩO´ÿÁ´ÄŒÖé–L§Œé–L§ÿÁ´ÄkÉ~é–L§Ú ˜‡–žm" ˆ£žÿ§ˆ£ŒÖé–L§Œé–L§Úu) É~é–L" s ŒÖžÿ§L«Œ±N^accept ¼ê " clientsocket ŒÖžÿ§L«Œ±N^recv ¼ê " du¤kŠéÑ´^S‰1§vk¿1§S§Ø¬ÑyÀâ¯K" …Œ [ú^Ә‡?§S˜m§ƒpÏ&Ø¤¯K" ´XJhandledata ¼ê?ns éÈžm§½ök̂ §@oÒ¬{Ž #랦§ÚÙ¦^rêâ?n"Ožÿ‡%" e‡?nƒ'Ü© §3.9 Âe‡ §3.10 POP3 Æ0 §3.10.1 ˜‡{ü~f POP3(Post Office Protocol - Version 3) ù‡Æ^u½ÂràXÛlÑÖìà e‡" Ï~§POP3 ÑÖì3110 àifTCP 랦"ràuå랦§ÚÑÖì ïáTCP ë" e¡´˜‡~f: S: C: S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us> C: APOP mrose c4c9334bac560ecc979e58001b3e22fb S: +OK mrose’s maildrop has 2 messages (320 octets) C: STAT S: +OK 2 320 C: LIST S: +OK 2 messages (320 octets) S: 1 120 S: 2 200 S: . C: RETR 1 S: +OK 120 octets annCharles@tom.com 1150,208 Python ÆS)P §3.10 POP3 Æ0 S: S: . C: DELE 1 S: +OK message 1 deleted C: RETR 2 S: +OK 200 octets S: S: . C: DELE 2 S: +OK message 2 deleted C: QUIT S: +OK dewey POP3 server signing off (maildrop empty) C: S: §3.10.2 ¦^POP3 ÆÂe‡ ÑÖìÂ랦§ux˜‡¯ÿŠ" S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us> ,§ràÒux·-§ÑÖìux·-A"z˜‡·-Ñ´k˜1" ˜1½ÂÒ´±CRLF (£†1)(—˜ãêâ" z‡·-k˜‡'…i(Keyword)§L«·-¶¡§´4 ‡i1§XLIST, STAT  "k·-‘këê§^˜‡˜‚©mëêÚ·-" éuk·-§ÑÖìA¹k˜1"1˜11˜‡cŒU´“+OK” ½ö“- ERR” ©OL«~ÚÉ~œ¹" §3.10.3 õ1A?n k˜ ·-§ÑÖìA¹kõ1"A(åI“´==¹˜‡:2 §“.”  1"XJê⥹k±“.” mÞ1§@oÒrù‡:Uü‡:“..” §Âà-ù 1§Ò¦´êâ§r¦¡EL5Ò1 " uxà?nXe: for line in uxêâ¤k1: if line.find(".")==0) : #± . mÞ line="."+line ux line 2=©¥éÒ annCharles@tom.com 1151,208 Python ÆS)P n Python ~^¬ # vkêâ ux ".\r\n" Âà?nXeµ for line in Âêâ¤k1: if line == ".\r\n" : break # Â(å if line.find("..")==0) : #± . mÞ line= line[1:] # K˜‡ . V\ line Aêâ¥" §3.10.4 POP3Ï&L§¥G ràÚÑÖìàÏ&L§¥kn‡Gµ AUTHORIZATION ïáTCP 냧?\TG"ÑÖ앐ràux¯ÿŠ" TRANSACTION ràJø^r¶¡Ú—觤õ¹§ÑÖìàéràe ‡§r©] "3ù‡G¥§rÚÑÖìàm©p·-" TRANSACTION ÑÖìÂQUIT ·-§?\TG§3ù‡G¥§º˜r ©] §¤^rJöŠ§'4TCP ë" 3AUTHORIZATION G§kü«Jø—èÚ^r¶¡ª" 1. ¦^USER ÚPASS ·-|Ü" 2. üÕ¦^APOP ·-" §3.10.5 POP3¥·- e¡0 ˜ė·-: 1. USER - ‚ª: USER name - ëê: name ^u½^r¶¡ - ^å: 3AUTHORIZATION G¥§ÏÑÖì^r¶¡" - A: annCharles@tom.com 1152,208 Python ÆS)P §3.10 POP3 Æ0 +OK name is a valid mailbox -ERR never heard of mailbox name - ~f: C: USER frated S: -ERR sorry, no mailbox for frated here ... C: USER mrose S: +OK mrose is a real hoopy frood 2. PASS - ‚ª: PASS string - ëê: string ^u½^r—è - ^å: 3AUTHORIZATION G¥§ÏÑÖì^r—è" - A: +OK maildrop locked and ready -ERR invalid password -ERR unable to lock maildrop - ~f: C: USER mrose S: +OK mrose is a real hoopy frood C: PASS secret S: -ERR maildrop already locked ... C: USER mrose S: +OK mrose is a real hoopy frood C: PASS secret S: +OK mrose’s maildrop has 2 messages (320 octets) 3. APOP - ‚ª: APOP username digest - ëê: username ^uJø^r¶¡"digest ^uJø\——è - ^å: 3AUTHORIZATION G¥§ÏÑÖì^r¶¡Ú—è" XJ¦^USER ÚPASS |ܧ@o^r¶¡Ú—è¦^²©3ä¥D4§ ùkSۇ"APOP ·-Ò´ \S˜«@yś" annCharles@tom.com 1153,208 Python ÆS)P n Python ~^¬ XJ˜‡ÑÖì|±APOP ·-§@o3¯ÿŠ¥¹˜‡iÎG§ ‰timestamp §3Unix XÚ¥§˜„´e¡‚ª Ù¥process-ID ´?§Ò§clock ´ÌÅ$1žm§hostname ´ÌÅ ¶"ùz˜g¹§Ñ¬kؘtimestamp " rtimestamp()k)Ò)ڗèÜ3˜å\—§digest Ò´\——©§\ —Ž{´RFC 1321 ¥MD5 "digest ´˜‡¹k16‡i!iÎG§´˜‡é Œê›8?›L«" - A: +OK maildrop locked and ready -ERR permission denied - ~f: S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us> C: APOP mrose c4c9334bac560ecc979e58001b3e22fb S: +OK maildrop has 1 message (369 octets) 3ù‡~f¥§XJ—è´tanstaaf @o‡\—iÎG´: <1896.697170952@dbc.mtview.ca.us>tanstaaf \—)—©´µ c4c9334bac560ecc979e58001b3e22fb 4. STAT - ‚ª: STAT - ëê:à - ^å: e‡¥e‡êþ - A: +OK nn mm Ù¥nn L«e‡‡ê§mm L«e‡¥¤ke‡¤Ói!ê" - ~f: C: STAT S: +OK 2 320 ù‡e‡¥küµ&§Ó320 ‡i!" 5. LIST annCharles@tom.com 1154,208 Python ÆS)P §3.10 POP3 Æ0 - ‚ª: LIST [msg] - ëê: msg ë괌À§XJvkJøù‡ëê§@oT·-A¹õ 1§z˜1²˜‡e‡Œ"XJJø ù‡ëê§@o҈£½e‡ Œ" - ^å: we‡Œ - A: +OK scan listing follows -ERR no such message - ~f: C: LIST S: +OK 2 messages (320 octets) S: 1 120 S: 2 200 S: . ... C: LIST 2 S: +OK 2 200 ... C: LIST 3 S: -ERR no such message, only 2 messages in maildrop õ1A¥§¹“.” 1L«A(å"z˜1§¹ü‡êi§c¡e ‡Ò觡´e‡Œ§±i!ü " 6. RETR - ‚ª: RETR msg - ëê: msg ²‡Â=µe‡" - ^å: Âe‡" - A: +OK message follows -ERR no such message XJˆ£~§^õ1L«e‡SN"õ1A¥§¹“.” 1L«A (å"ê⥹k±“.” mÞ1§3mÞ\˜‡“.” §Â౓.” mÞ 1§T1Ø´¹“.” 1§@oíØmÞ“.”" - ~f: annCharles@tom.com 1155,208 Python ÆS)P n Python ~^¬ C: RETR 1 S: +OK 120 octets S: S: . 7. DELE - ‚ª: DELE msg - ëê: msg ½‡íØe‡Òè" - ^å: ‰e‡e‡‹þíØIP§XJ¡·-§3¢ÚTe‡§@oÒéØ  "´e‡vkýíاkÏLQUIT ·-§~?\UPDATE  G§e‡â¬íØ" - A: +OK message deleted -ERR no such message - ~f: C: DELE 1 S: +OK message 1 deleted ... C: DELE 2 S: -ERR message 2 already deleted 8. NOOP - ‚ª: NOOP - ëê:Ã" - ^å: ˜öŠ" - A: +OK - ~f: C: NOOP S: +OK 9. RSET - ‚ª: RSET - ëê:Ã" annCharles@tom.com 1156,208 Python ÆS)P §3.10 POP3 Æ0 - ^å:XJe‡DELE ·-‹þ íØIP§@oÒKIP§Ò´¡E¤ kíØe‡" - A: +OK - ~f: C: RSET S: +OK maildrop has 2 messages (320 octets) 10. QUIT - ‚ª: QUIT - ëê:Ã" - ^å:?\UPDATE G§ÑÖìù‡·-ƒ§¬ýíؤk‘kí ØIPe‡§º˜ràž] "'4TCP ë" - A: +OK -ERR some deleted messages not removed - ~f: C: QUIT S: +OK dewey POP3 server signing off (maildrop empty) ... C: QUIT S: +OK dewey POP3 server signing off (2 messages left) 11. TOP - ‚ª: TOP msg n - ëê: msg ²e‡Òè§n ²1ê" - ^å:ÚRETR aq§´==Âe‡©¥n 1§Ø)e‡Þ"e‡Þ Úe‡©^˜1©…" - A: +OK top of message follows -ERR no such message - ~f: C: TOP 1 10 S: +OK annCharles@tom.com 1157,208 Python ÆS)P n Python ~^¬ S: S: . ... C: TOP 100 3 S: -ERR no such message 12. UIDL - ‚ª: UIDL [msg] - ëê: msg ´ŒÀ§²e‡Òè" - ^å:ÚLIST ·-aq§´ˆ£Ø´e‡Œ§ ´e‡unique-id ˜ ‡˜I£" unique-id ´˜‡iÎG§ŒÝ´70 §iΌ±´0x21–0x7E ¥?¿˜ ‡"ù‡unique-id ´z˜‡e‡˜§zg¹¦ÑجC" - A: +OK unique-id listing follows -ERR no such message - ~f: C: UIDL S: +OK S: 1 whqtswO00WBw418f9t5JxYwZ S: 2 QhdPYR:00WBw1Ph7x7 S: . ... C: UIDL 2 S: +OK 2 QhdPYR:00WBw1Ph7x7 ... C: UIDL 3 S: -ERR no such message, only 2 messages in maildrop §3.11 ^poplib ¬Âe‡ #!/usr/bin/env python # pop3example1.py import sys,os,poplib annCharles@tom.com 1158,208 Python ÆS)P §3.11 ^poplib ¬Âe‡ def main(): SERVER = "your.email.pop3.server" USER = "username" PASSWORD = "password" # connect to server server = poplib.POP3(SERVER) # login server.user(USER) server.pass_(PASSWORD) # list items on server resp, items, octets = server.list() for item in items: id,size = items.split(" ") # download a random message resp, text, octets = server.retr(id) print "---------------mail No.%d---------------------" print text.join("\n") # be careful, your email will be deleted # server.dele(id) server.quit() if __name__ == "__main__": main() `²µ 1. poplib.POP ˆ£˜‡server 閧3POP Щz¼ê¥§¬¦å•ÑÖìïáë §¿…ÑÖìux¯ÿŠ"XJØUïáë§@oÒÑsocket.error É~" 2. server.user Úserver.pass_ ·-§•ÑÖì@y¹"XJ¹Ø¤õ§@o Ñpoplib.error_proto É~"XJ˜‡·-AØ´±“+” mÞ§@où‡· -ѬÑùÉ~" 3. server.list e‡L"resp ´A¥1˜1"items ´˜‡list §^S¹ õ1A¥z˜1"octets ´õ1A¥i!‡ê"…´õ1A·-§ˆ£ Ñ´aq" 4. server.retr ^5Âe‡"server.dele ^5íØe‡"íØe‡ù˜1§5º K §Ï“襍´rÂe‡print Ñ5§¿vk;§¤±„ØÜ´íØe ‡" annCharles@tom.com 1159,208 Python ÆS)P n Python ~^¬ ¼ê¶¡ £ã p=server(servername,portnumber) ïáë"ˆ£é–p§|±e¡¼ê" p.user(strUser) ux^r¶¡"strUser ´iÎG" p.pass (strPass) ux—è"strPass ´iÎG" p.stat() e‡G"ˆ£˜‡tuple §¹kü‡ êi§L²e‡‡ê§Úe‡Œ" p.list(which=None)   e ‡ , ˜ µ e ‡  Œ  "XJ  ½which @oˆ£˜‡ü1A§XJØ ½§ˆ£õ1A" p.retr(msg) Âe‡"ˆ£˜‡tuple §¹kn‡ƒ§ ©O´õ1A¥1˜1§z˜1ê⧠ÚêâŒ" p.dele(msg) íØe‡"ˆ£ü1A" p.noop(msg) ˜öŠ"ˆ£ü1A" p.rset() ¡EíØe‡"ˆ£ü1A" p.apop(username,password) ^APOP ·-@y" p.top(which,howmuch) Âe‡Þ§Úretr ˆ£aq" p.uidl(which=None) Úlist aq§ˆ£e‡˜I£" L 3.11-10: poplib ·-o( lù‡~fŒ±w§poplib ¥¤k·-AÑÚPOP3 Æ5½ƒ˜—" poplib ·-o(XL3.11-10 §3.12 SMTP Æ0 SMTP( Simple Mail Transfer Protocol) ´{üe‡DÑÆ"¦¿Ø6†.D ÑƧ‡¦k˜‡Œ‚6Ï(stream channel)"SMTP ¦^DÑÆ¥§A^ 2´TCP Æ" SMTP ˜‡Ì‡Š^Ò´|^DÑÑÖ(transport service) Jø?§mÏ&‚ ¸(interprocess communication environment,IPCE) 3ÌŃm=u(relay) e‡" §3.12.1 SMTP˜‡~f S: HELO Alpha.ARPA R: 255 Beta.ARPA welcome S: MAIL FROM: R: 250 OK S: RCPT TO: annCharles@tom.com 1160,208 Python ÆS)P §3.12 SMTP Æ0 R: 250 OK S: RCPT TO: R: 550 No such user here S: RCPT TO: R: 250 OK S: DATA R: 354 Start mail input; end with . S: Blah blah blah... S: ...etc. etc. etc. S: . R: 250 OK SL« u x  §RL«    " ù ‡ ~ f ¥ § u x   e ‡ / Œ ´ §   e ‡  < k n ‡ § © O ´ §§ " SMTP uxÚpžÿ§uxux˜‡·-§Â·-§?n §‰ÑƒAA" kn‡…À« 1. forward path …À«"^u;forward path " forword path (c•´») ´e‡ˆÂ‡<´»"~X: @HOSTA.ARPA,@HOSTB.ARPA:Smith@HOSTC.ARPA L«ªÂ‡< /Œ´Smith@HOSTC.ARPA §´&‡‡ˆ8 /§7 L²LHOSTA.ARPA ÚHOSTB.ARPA =u"kÒc¡ÌŶ¡§^ÏÒ © … § L« e ‡  ˆ  ª  ‡ <  ´ »"XJØ  ½ = u ÌÅ § @ o Ò  ¤Smith@HOSTC.ARPA Ҍ± " 2. reverse path …À«"^u;reverse path " reverse path (•´»)´e‡ˆ£u‡<´»"¦LˆªÚforward path ˜"XJe‡ØUˆu‡<§@ok)˜‡†Øϧù‡Ïe‡¬÷ Xreverse path §ux‰u‡<" 3. êâ…À«"^u;uxe‡" k·-¬én‡…À«K" annCharles@tom.com 1161,208 Python ÆS)P n Python ~^¬ §3.12.2 uxe‡·- ƒp¯ÿ Ï&ëffïážÿ§Âàux˜‡¯ÿŠ"~Xµ 220 USC-ISIF.ARPA Service ready SP ÚCRLF ©OL«˜‚Ú£†1"USC-ISIF.ARPA L«ÂàÌŶ¡"¡‹X ¯ÿŠ" ù´Ï~A"XJÑÖìѯK §ŒU¬ˆ£421 †Ø§L«e‡ÑÖÑ ¯K §ë¬'4" uà¯ÿŠ§uxHELO ·-" S: HELO USC-ISIF.ARPA R: 250 BBN-UNIX.ARPA HELO ·-¡ëꍲuàÌŶ¡" Âà¤õA´250 §¡´gCÌŶ¡" X3u& MAIL ·-^5²reverse path "~X: S: MAIL FROM: R: 250 OK MAIL ·-‚ª¥“FROM:” ¡´reverse path "XJuà´=ue‡§@o¦¬ 3reverse path ¥¹gCÌŶ¡\reverse path cà" XJ¤õ§ÂàA250 "”}{§ŒUˆ£XeA: 552 e‡;˜mØ " 451 /?nц" 452 XÚ;˜mØ Ñ†{§ŒUˆ£XeA: 500 Š{†Ø§Ã{£O·-" 501 ëꥊ{†Ø" 421 ÑÖì”~§ëò'4" Âà¤õ‰1ù^·-§˜˜¤k…À«§r“FROM:” ëê¥forward path \\ reverse path …À«¥" ·‚§XJe‡ux”}§Ò¬)˜‡†ØÏe‡§ux‰u‡<§´§ ù‡žÿXJ2½reverse path {§@où‡†ØÏe‡XJux”}{§Ò¬ )˜‡†ØÏe‡†ØÏe‡§ù̂eŒØ´˜‡Ð¯§¤±§MAIL ·-¥ reverse path Œ±´˜§L«XJe‡ux”}§Ø‡ux£‰e‡ux< "~X: annCharles@tom.com 1162,208 Python ÆS)P §3.12 SMTP Æ0 MAIL FROM:<> 3ux†ØÏe‡žÿ§Ñ´Ø½reverse path §ùÒ; e‡Ì‚" u‰X& RECP ·-^5²forward path "~X: S: RCPT TO: R: 250 OK S: RCPT TO: R: 550 No such user here S: RCPT TO: R: 250 OK z˜gRCPT ·-¤õƒ§Ò¬3forward path ¥O\˜‡V¹"z˜‡forward path XJ½ =uÌŧ@o˜½‡÷X=uÌÅ^S§g=u"˜„5`§Âà ´forword path ¥1˜‡=uÌŧ½ö´ª8/" XJ´=uÌŧ@o¦Òeg=uùµe‡žÿ§Ò¬r¦gC¶ilreverse path 1˜‡ÌŶ¡¥£r§\forward path ¥" &SN´Ÿo DATA·-^uuxe‡SN"~Xµ S: DATA R: 354 Start mail input; end with . S: Blah blah blah... S: ...etc. etc. etc. S: . R: 250 OK Âà¬@¡¤k1Ñ´e‡SN"uxêâžÿÚPOP3 Æaq§^˜ ‡¹k“.” 1L«êâ(å"XJê⥹k±“.” mÞ1§Ò3mÞ\˜‡“.”§ ,¦Ø==¹˜‡“.” §Âà3É¥3K\“.” §¢y êâß²DÑ" êâ¬V\3êâ…À«S" ÂàÂêâ.§AT?nn‡…À«¥&E§?n.§˜˜¤k…À«" XJ¤õ?n …À«S&E§ÂàAT£A250 OK " Âà„¬3e‡êâmÞO\˜1§‰eZ§time stamp "ù§z˜‡ÌÅÑ ¬3þ¡‹˜‡eZ§@o‡<Â&žÿ§¦ÒŒ±e‡´Nolu‡<@p ˆ" annCharles@tom.com 1163,208 Python ÆS)P n Python ~^¬ XJÂഁ˜‡ÌŧÒ´8Ìŧ@oTÌń¬3e‡êâmÞO\˜ 1§‰return path §ù˜13 MAIL ·-¥reverse path &E" ùÒ¿›X§ªÂ‡ Received: from GHI.ARPA by JKL.ARPA ; 27 Oct 81 15:27:39 PST Received: from DEF.ARPA by GHI.ARPA ; 27 Oct 81 15:15:13 PST Received: from ABC.ARPA by DEF.ARPA ; 27 Oct 81 15:01:59 PST Date: 27 Oct 81 15:01:01 PST From: JOE@ABC.ARPA Subject: Improved Mailing System Installed To: SAM@JKL.ARPA This is to inform you that ... Ù¥1˜1“Return-Path” ´˜‡e‡ÑÖìO\§3 MAIL ·-¥ ëê"¡n1´§z˜‡ÑÖìXeZ"ùw Œ±§JOE kuxe ‡lABC.ARPA DEF.ARPA §DEF.ARPA GHI.ARPA §GHI.ARPA JKL.ARPA §JKL.ARPA ´Â‡ S: VRFY Smith R: 251 User not local; will forward to S: VRFY Jones R: 550 String does not match anything. S: VRFY Jones R: 551 User not local; please try S: VRFY Gourzenkyinplatz R: 553 User ambiguous. 1˜‡~f¥§£x250 A§L«e‡Œ±†ux‰Smith "A¥¹kSmith ^r¶¡" 1‡~f¥§£x251 A§L«e‡ØŒ±†ux‰Smith §´ÂàŒ±ÏL Ù§ÌÅ=u‰Smith " 1n‡~f¥§£x550 A§L«e‡ØŒ±†ux‰Smith §ÂàØŒ±ÏL Ù§ÌÅ=u‰Smith §´ÂàwŠuàŒ±Á˜ÁÙ¦ÌÅ, USC-ISIQ.ARPA " 1o‡~f¥§£x553 A§L«Ø˜‡^rGourzenkyinplatz " ù‡·-جén‡…À«E¤K" EXPN EXPN ·-^r*И‡e‡L¶¡"EXPN ë괘‡e‡aL¶¡§ÂàX Jù‡e‡L¤k^r§@oÒ¬rù‡e‡L¥¤k^rˆ£‡uà"~ X: S: EXPN Example-People R: 250-Jon Postel R: 250-Fred Fonebone R: 250-Sam Q. Smith R: 250-Quincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA> R: 250- R: 250 z˜1ѝ¹˜‡^r¶¡"5¿õ1A¥250 ¡‘k~Ò§L«„k A" annCharles@tom.com 1165,208 Python ÆS)P n Python ~^¬ ù‡·-جén‡…À«E¤K" SEND SOML SAML SEND ·-ÚMAIL ·-aq§ØÓ´§XJ^r¹ ˜Ìŧ@oSEND · -´re‡ux^rªàþ§ Ø´^re‡¥" 5>fe‡^rÑ´¹ARPA net þ˜ÌÅâU w>fe‡"XJ ^r¹ž§ÒŒ±†uxe‡^r¹ªàþ " ´y3õ^r´¦^POP3 ÆlÌÅþe1e‡/Ö§ Ø´¹e‡ ÑÖìþ " XJ^rvk¹§@oÂà¬ux”}A" SOML ·-¿g´SEND or MAIL §L«uxe‡^rªàþ§½öux^ re‡¥" SAML ·-¿g´SEND or MAIL §L«uxe‡^rªàþ§¿…ux^ re‡¥" HELP Âàù‡·-§•uàuxÏ&E"ù‡·-Œ±‘kÙ¦·-‰ëê§^ u,˜‡A½·-Ï&E" ù‡·-جén‡…À«E¤K" NOOP ˜öŠ"Âào´ˆ£250 OK " TURN ^u†uxàÚÂ৏Ҵù‡·-ƒ§uxàCÂà§ÂàCux à" XJïáÏ餞m½ö7a§@oF"3˜gë¥Óž¤uxÚ§ù‡· -Òék^" 3IP ¥TCP ëØ´é[B§¤±˜„Ø^ù‡·-" §3.12.4 ESMTP §3.12.5 ¹@y annCharles@tom.com 1166,208 Python ÆS)P 111oooÙÙÙ Tkinter ???§§§ §4.1 Tkinter0 §4.1.1 Ÿo´Tkinter Tkinter ´˜‡python ¬§´˜‡N^Tcl/Tk "Tcl/Tk ´êØõ( N´˜)ª² ã/.¡" 3ŒõêUnix ²þÑkTcl/Tk"y3Windows ÚMacOS þŒ±¦^Tcl/Tk Tk  .C Šó3Äë¥ tkinter ¥§Tkinter.py ´|^ tkinter ˜ ‡Python C§^uPython ^rJø" XÚgXã4-1e§±X windows ~µ Your App Here(Python) Tkinter(Python Module) tkinter(C) Tk Widgets(C and Tcl) Tk(C) Xlib (C) ã 4-1: Tkinter XÚgã Your App Here (Python) Python A^§S§N^Tkinter.py gv Tkinter (Python Module) Tkinter.py ^urPython ¥Lˆª=C¤Tk ·- Úëê" tkinter (C) ^urTkinter.py )¤Tk ·-Úëê§D4‰Tk )ºì§4Ù)º‰ 1" annCharles@tom.com 1167,208 Python ÆS)P o Tkinter ?§ Tk Widgets (C and Tcl) Tk ´dCژܩTcl ¤" Tk (C) Tk .C ŠóÜ©" Xlib (C) N^X ¥§ÚX Server Ï&" Python ^rج†N^ tkinter § ´ÏLTkinter.py m¦^¦" Tkinter Ø´˜Python ã/?§§´Ù¥'61˜‡"ŒA:´ª ²"²w":´5UØЧϏTcl/Tk ´)º5Šó§Python ´§^Python )¤Tcl/Tk “è§,2^Tcl/Tk )º‰1§„Ý,'†N^.ã/‡ú§ ù´¦ª²¤GÑ“d"´Œõꜹe§\جïá¤Zþ‡UܧI jº¤±˜„´Œ±÷v‡¦" ˜„¦^Tkinter {´ from Tkinter import * Œ±´ import Tkinter ´Tkinter z‡¼êÚac¡Ñ‡kTkinter.somefunc() §å5餞m" Ÿo´Widget ? Widget ´Button(UÜ) §Canvas(xÙ) §Menu(èü) §Label(ü 1 I\) §Message(õ 1 I\) §Listbox( L) §Entry (ü 1 Ñ\ µ) §Frame(µ e) §Radiobutton(õ«À˜üÀµ) §CheckButton(EÀµ) §Scrollbar( EÄ^) §Text(õ 1©Ñ\µ) §Scale(3˜½‰ŒSÀJ˜‡êŠEÄ^) TopLevel(I) Ú¡" Ÿo´option ? ¤kWidget Ñkéõoptions §)fg(cµÚ) §bg(µÚ) §font(iN) §command(¯‡?n¼ê) §text(SN) " §4.2 Hello Tkinter §S §4.2.1 {ü~f ÆSŠóÑ´l“Hello World” m©§·Ø»~" # File: hello1.py # \ Tkinter from Tkinter import * #M root Widget #Ï~z˜‡ Tkinter §SÑk˜‡§ …k˜‡ # root widget annCharles@tom.com 1168,208 Python ÆS)P §4.2 Hello Tkinter §S # ¦´˜‡{üI§‘kIK9§Ú>µÚÙ¦ Windows # Manage JøC»" # 7L3MïÙ¦ Widgetƒc§Mï root widget" # Œ±ØMï§Tkinter ¬gď\M" root = Tk() #M Label§ w§ # root ´ w  master(II)§ # w ´ root  slave (fI) # ùpâŠk:ØÓu Windows§ Windows e # ´ parent window§ Ú child window" # text ´ w ˜‡ option (À‘)§L« w ¥ # ‡w«SN§Œ±´©i½öã¡" w = Label(root, text="Hello, world!") # w M¿vkýw«3¶4¥§ # k3 pack ƒ§âUŠâ Label ¥SN§OŽÐ # Label Œ§˜ ˜§,w«3¶4þ" w.pack() #?\¯‡Ì‚§Â5g^r¯‡§‰1éA # ¯‡?n§†^rN^ quit() ½ö I'4 " # mainloop() „‡?nSÜ widget #§5g #Ú Windows Manager Ï&" root.mainloop() $1§S %python hello1.py $1(JXã4-2 ã 4-2: hello1.py $1(J ^B0 ˜eWM(Windows Manager)§ÙGX Windows ^rNéWMج))" ´Windows ^rÒ¬é)) "3X NX(¥§I>µ§IK9§'4Uܧ Œz§z§I£Ä§˜Œ §Ñ´WM 5‰§WM ØL´˜‡ÊÏ annCharles@tom.com 1169,208 Python ÆS)P o Tkinter ?§ X Client§ÏLIOÆÚX Server Ï&"?ۘ‡X client §Sь±ÚWM 5Ï&" 3Windows XÚ¥§WM Ú‡öŠXÚÜ3˜å§éJ©˜Ù§´·lWin XP ÚWin 2000 w§k˜ Windows §SŒ±ÏL,«Å›¤WM õU§4Windows  *wå5”MacOS §½öX eÙ¦WM J" §4.2.2 ,˜‡{ü§S 3˜‡'Œ§S¥§Ðr˜‡\§S3˜‡a¥§Xe # File: hello2.py from Tkinter import * class App: def __init__(self, master): #M Frame ^u¹Ù¦ widget frame = Frame(master) frame.pack() #MUÜ self.button = Button ( frame, # master widget text="QUIT", fg="red", command=frame.quit ) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi ) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() $1(JXã §4.2.2 XJ\U”Hello” Uܧ¬3››þ‹<“hi there, everyone!”" XJw ´˜‡widget§w.pack(side=LEFT) L«{˜w ª" annCharles@tom.com 1170,208 Python ÆS)P §4.3 Widget ˜ ã 4-3: hello2.py $1(J §4.3 Widget ˜ Tk ¥z˜‡widget Ñkéõoption §ÏLUCù option Œ±UCwidget  *" ;.option k››w«SN§ôÚ§Œ§¯‡?n¼ê§Tkinter Jø ژ .¡^u?n¤koption. Ï~k±e{?nwidget option: • Œ±¦^e¡{3Mïwidget žÿ˜widget options" widgetclass (master , option= ...) ~X: w = label(root,text="hello",fg="red") Mwidget §‰w §¦master widget ´root §¦option ¦^¡ëê 5‰½"¤kwidget option Ñk%@Š§¤±{üMwidget { ´¤koption Ѧ^%@Š§Ò´Ø½?Ûoption§I½widget master widget§XJ\éB{§$–ëmaster widget Œ±Ø^½§Tkinter ¬^C ¦^Lmaster widget Š%@master widget " • w.cget(option) ˜‡widget option Š"w ´˜‡widget "¤kwidget class Ñkr__getitem__ N w.cget þ§¤±¦‚ü‡vkŸo«O"¤± ^w[option] ˜Œ±˜‡option "~X: w = Label(text="abc") print w.cget("text") print w["text"] # vk«O§ÑŒ± abc ·úw[’text’] ªÐw˜ " • ^w.configure ½öw.config ˜option Š"w.config ´w.configure  §¤ ±õUþvk«O"^{ÚMïwidget žÿ˜" w.config(option=, ... ) ~X: annCharles@tom.com 1171,208 Python ÆS)P o Tkinter ?§ w.config(text="xxx") ¤kwidget class r__setitem__ N w.config þ§¤± w["text"] = ’xxx’ J˜" XJkéõoption ‡˜§@o^config Ðw˜ "XJk˜‡options ‡ ˜§@o^¡ªÐw1" • config ¤ ¼êXJؑ?Ûëê§@o¬˜‡widget ¤kŒ±˜option ¶¡"w.keys() ˜"·U¦^w.keys() §¦¿Â˜Ù§{ü"~X: for k in w.keys(): print "%s = %s"%(k,w[k]) Œ±‹<˜‡widget ¤koption " nþ¤ã§–¯˜‡widget option kü@{" w.config() w.keys() w.config(optionname=optionvalue,...) w[’optionname’]=optionvalue w.cget(’optionname’) w[’optionname’] äN¦^@«d‡þ"Œ±´TOP (þ) §BOTTOM( e)§LEFT( †)§RIGHT( m)" padx ÚÚÚpady L«parcel z˜‡>Úw ƒmý3˜m" ipadx ÚÚÚipady L«wz˜‡>Úw S¹SNƒmý3˜m"w ¬ÏdCŒ" fill Œ±´None, x, y , both"XJparcel Œ §@oÒ¬Šâfill Š§O\slave widget Œ" • None: L«‘±slave widget 5Œ" •X:L«*Œslave widget °Ý" •Y:L«*Œslave widget pÝ" • BOTH: L«Óž*Œslave widget °ÝÚpÝ" Š5¿§fill ´slave widget ŒÚparcel Œƒm'X§û½slave widget NUCgCŒ§5·Aparcel Œ" annCharles@tom.com 1173,208 Python ÆS)P o Tkinter ?§ anchor L«3parcel ¥˜˜slave widget ª"Œ±´±eŠ""ŽŠ´CENTER" W ‚†˜˜ E ‚m˜˜ N ‚þ˜˜ S ‚e˜˜ NW ‚†þ˜˜ NE ‚mþ˜˜ SW ‚†e˜˜ SE ‚me˜˜ CENTER ˜3¥m ùpŠ5¿´§XJfill Š´X §@oanchor ´WÚEÒä¢ §Ïslave widget °Ý®²´Œ§‚†˜„´‚m˜ÒvkŸo¿Â "Ón§XJfill Š´Y §@oanchor ´NÚSÒä¢ "XJfill Š´BOTH §@oanchor option Òvk¿Â "ùéØЧgrid +nì3ù˜:þkU?" expand Œ±´0 ½ö1"XJ´1 §L«slave widget ¬Šâe¡¤`{§rmaster  {˜m©‡z˜‡slave widget parcel"XJ´0 §4{˜m˜X" Š5¿´§expand ´master {˜mÚ¤kslave widget parcel ƒm'X XJr¤kslave widget Ñ{˜Ð §´„k{˜m§¦¬û½´Ø´rmaster {˜m‰¤kparcel " 5¿§±þ¤koption Xside§padx , pady , ipadx , ipady , expand, fill Ñ´N ^pack() ž½option§ Ø´Mïwidget žÿ½option" Pack Ž{ z˜‡master widget Ñk˜‡packing list ^u+n¦Sܤkslave widget"Mï˜ ‡#slave widget§¬3master widget Packing list (—J\˜‡slave widget"„Œ ±^in , after , before ùn‡option UC^S" Pack +nìUìpacking list owidget ^S§˜˜{˜z˜‡widget"3fm ©§master widget Sܤk˜mÑ´˜§Ò´cavity (˜É)" Pack Uì˜eÚ½¿Â{˜z˜‡slave widget" 1. ÷X˜‡cavity ˜‡>ƒe˜‡Ý/§‰parcel (K)§äN÷=˜‡>´dside option ½" XJside = TOP ½öside = BOTTOM §@oparcel °ÝÒ´cavity °Ý§pÝ Ò´slave widget ‡¦pݧ2\þpady Úipady ùü‡options ¤½êŠ" XJside = LEFT ½öside = RIGHT §@oparcel pÝÒ´cavity pݧ°Ý Ò´slave widget ‡¦°Ý§2\þpadx Úipadx ùü‡options ¤½êŠ" ±parcel „ŒUϏexpand option ¤½Š CŒ"XJ¤kslave widget Ñ ˜Ð§uymaster widget „kõ{˜mvk¦^§@oÒ¬Šâexpand option annCharles@tom.com 1174,208 Python ÆS)P §4.4 Geometry Manager(AÛ+nì) 5UC¤kparcel Œ"XJexpand option ´0 §@oҎ §Ò4@ ˜ /˜XÐ "XJexpand option ´1 §@oÒre˜mþ!©‰¤k parcel"XJ˜‡Œ±*Œslave widget side option ´left ½öright §@orõ {Y²ål¬²þ©¦‚"XJ˜‡Œ±*Œslave widget side option ´top ½öbottom §@orõ{R†ål¬²þ©¦‚"ùé"y(¹5§grid + nìO\ ­Vg§´k¤U?" 2. pack +nìslave widget ÀJÜ·pÝÚ°Ý"°Ý˜„´widget ¤I°Ý\þü ipadx §pÝ´˜„´widget ¤IpÝ\þüipady §Ÿo´ü? ´Ï †mÑI‡3Ñipadx ål§ÓþeÑI‡õ3Ñ5ipady ål"´XJfill option ŠXJ´X ½öBOTH§@o*Œ°Ý§slave widget °Ý¬´parcel ° Ý~üpadx Š§ÓXJfill option Š´Y ½öBOTH §@oslave widget °Ý¬´parcel °Ý~üpady Š§ 3. pack +nìrslave widget ˜3parcel ¥"XJslave widget 'parcel §@oҊ âanchor option 5˜˜slave widget§parcel e˜mØ¬‰Ù¦slave widget ¦ ^ "XJpadx option ½öpady option ŠØ´0 §@o3parcel >.Úslave widget >.ƒmo´‡3Ñ5padx Úpady @oõ˜x˜m" ˜˜Ð˜‡slave widget §pack +nì¬~parcel §e˜‡'cavity ^ 5˜˜e˜‡slave widget"XJcavity ˜mØ ˜˜˜‡slave widget §@où‡slave widget ¬Óâcavity ¤k˜m"cavity  –0 žÿ§Ù¦eslave widget Ò wØ §Øšmaster widget CŒ" ˜„œ¹emaster widget ¬gÄCŒ§âŠ‰Geometry Propragation (AÛD§ ŒDÂ)"Geometry propragation ¿gÒ´`§gÄNmaster widget °ÝÚp ݧ^5И˜¤kslave widget §¿…¬3widget g(¥D4Œ"Ÿo ‰widget g(?·‚master widget Úslave widget 'X" master widget q ´,˜‡widget slave widget"ùҔ/¤ ”ŒŒ§IŠ§f§šfùg' X"Œ±`´ä“§äª§äŠ'X" ÄkOŽä“widget Œ§ä“widget vkslave widget §¦‚¬gCOŽgCŒ §v±NBe¤kslave widget ¤kSN§,¹ù‡äªwidget ŒҌ±Šâ ¦¤slave widget ŒUC§ù˜†•þD4§†TopLevel" ùª(JÒ´¤kWidget {˜›©Ün",§kžÿùØ´·‚Ž‡ (J§@o·‚Œ±ÏLN^e¡¼êʎGeometry Propagation" w.pack_propagate(’true’) ¦^Pack +nìžÿ§²~¬¦^frame widget §^ ur˜|widget w¤˜ ‡widget" annCharles@tom.com 1175,208 Python ÆS)P o Tkinter ?§ §4.4.2 Grid +nì ¦+Pack é؆§´§éõ§S @Grid +nìÐ^" … -<¬ ^Grid § Ø^Pack"N¦´é"·@ˆkˆ`:" ·@Grid +nìVg{ü§õUrŒ§(¹§(¢'Pack r˜ " ¦^Grid {é{ü§ÚPack aq§N^w.grid(options) §w ´˜‡slave wid- get" Grid +nìr˜‡master widget ¤kŒ^˜m©¤‚Géõ°"z˜ °‰˜‡Cell §ÚPack +nì¥parcel Vg郔"^row §column §rowspan §columnspan Ҍ±(½˜‡cell "ke~^option" ~^options row ²3@˜1 column ²3@˜ rowspan ²Ó A1 columnspan ²Ó A ipadx ipady ÚPack +nì¿ÂƒÓ"L«slave widget SÜO\W¿ål" padx pady L«slave widget >.Úcell >.ƒmW¿ål" sticky Œ±´N §W §S §E §¹ ´Pack +nì¥fill §anchor õU"L«Cell 'slave widget Œžÿ§XÛ{˜slave widget§7‡žÿ§O\slave widget p ݽö°Ý" XJ´ü‡NL«§•þ‚§aqPack +nì¥anchor= N " XJ´ü‡|ÜL«§XN+S §L«O\pݧaquPack +nì¥fill = Y " XE+W §L«O\°Ý§aquPack +nì¥fill = X " XJ ü ‡  | Ü ´N+E L«ØO\ p Ý ½ ° Ý § • m þ  { ˜ § ƒ  ufill=None§anchor=NE Ù§aq" XJ´õ‡|ÜN+W+S+E L«˜3¥m"aquPack +nì¥fill=BOTH " XJؘsticky Š§L«ØO\pݏØO\°Ý§˜3¥m§aquPack +n ì¥anchor=CENTER§fill=None " annCharles@tom.com 1176,208 Python ÆS)P §4.4 Geometry Manager(AÛ+nì) Grid +nìŽ{ kn‡Ú½: 1. OŽ–I‡õŒ/§ÒŒ±{˜e¤kslave widget " 2. ^þ˜ÚOŽ(JÚmaster widget ¢SŒ'§XJؘŒ§@oÒO\½ ö~master widget Œ" 3. Šâz˜‡slave widget sticky options §{˜¤kslave widget " 31˜Ú¥§ÄkOŽ¤kÓ˜1(½)cell °Ý(½pÝ)§Ò´rowspan=1 (½colspan=1)cell "z˜1(½) °Ý(½öpÝ)Ò´ù˜1(½)¥¤I‡Œ° Ý(½öpÝ)§±y˜e¤kslave widget "z˜1§z˜ŒÑ §ùz ˜‡cell ŒÒ(½ " ,3ÄÓõ1(½öõ)cell §cell ¤ÓëY1(½)‰˜‡cell group §cell group °Ý(½öpÝ)´|S¤kcell °Ý(½öpÝ)Ú"XJcell group Œ§v ˜eƒéAslave widget §@oÐ §‘±|S¤k1(½)°Ý(½p Ý)ØC"XJ˜Øe§ÒI‡O\|SCell z˜1(½)Ý(½pÝ)"O\{Ò´Š â1(½)weight(­)U'~5O\cell group ¥z˜1(ö)°Ý(öpÝ)§weight ŒO\õ§weight O\§weight ´0 ÒØO"XJcell group ¥¤kcell weight Ñ´0§@oÒ²þO\|S¤kcell °Ý(½pÝ)" ge§Œ±(½z˜(½1)°Ý(½pÝ)§ùz˜‡cell Úcell group Œ Ò(½ " ˜˜1weight§Œ±¦^grid rowconfgure ¼ê§~X m.grid_rowconfigure(0,weigtht=2) r101weight ˜2 " ˜˜weight§Œ±¦^grid columnconfgure ¼ê§~X m.grid_columnfigure(0,weigtht=2) r10weight ˜2 "Ù¥m ´¤kslave widget master widget" 31Ú¥§XJmaster widget š~Œ§„kéõ{˜m§@oÒ¬rR†(½ öY²){˜m©‰¤k1(½ö)§Šâz˜1(½ö)weight ŠU'~© §weight Œõ§weight §weight 0 Ø"XJ¤k1(½ö)weight Ñ´0 §@oÒrR†(½öY²){˜m²þ©3þe(½ö†m)ü৏Ҵإ ˜˜"ù§^weight Vg¤ Pack +nì¥expand option õU" nþ¤ã§Grid +nì¥option ‡'Pack +nì¥option ‡õ"´õU %'ƒ\(¹§\rŒ§Pack U‰§Grid AÑU‰§Grid U‰§Pack I‡˜ ˜éõframe Úéõoption âU¤" annCharles@tom.com 1177,208 Python ÆS)P o Tkinter ?§ Place +nì Place Œ±°(˜˜˜‡slave widget  ˜ÚŒ§aquVB ¥top§left §bottom §right á5"ùé憧˜„Ø^"XJ\ýI‡ùo‰§@oÒ ÃþÐ "–·6žØ¬^¦" §4.5 Widget ª dNõwidget Ñ|±Óoption §ù option ½Â widget Ī§) ôÚ§iN" §4.5.1 ôÚ Œ õ ê widget #N ^ r  ˜background option Úforeground option 5 UC ˜ ‡widget cµÚÚµÚ"cµÚ˜„´widget þ¡©iôÚ" bg Úfg ´background Úforeground {¡"XJ\‹i'ú½ö'B§@oÒ ^bg Úfg “Obackground Úforeground" 3½ôÚžÿ§Œ±†½RGB n‡©þŠ§Œ±½ôÚ¶i§ Xred, green " ôÚ¶i Tkinter ¹k˜‡ôÚê⥧^u¹¤kôÚ¶¡ÚôÚ¢SRGB ŠéA 'X"ê⥥¹~^ôÚ§Xµred , yellow , blue , green §lightblue §) ˜ Ø~^´é¤ôÚ§XMoccasin, PeachPuff, etc. 3X windows XÚ¥§ôÚ¶idX windows ½Â§Œ±3érgb.txt §˜„ 3/usr/X11R6/lib/X11/ 8¹eù‡©‡¥¹ ¤kôÚ¶iÚôÚRGB ŠéA 'X" 3Windows XÚe§Œ±¦^Windows XÚôÚ(Œ±ÏL››¡†UC) SystemActiveBorder, SystemActiveCaption, SystemAppWorkspace, SystemBack- ground, SystemButtonFace, SystemButtonHighlight, SystemButtonShadow, SystemBut- tonText, SystemCaptionText, SystemDisabledText, SystemHighlight, SystemHighlightText, SystemInactiveBorder, SystemInactiveCaption, SystemInactiveCaptionText, SystemMenu, SystemMenuText, SystemScrollbar, SystemWindow, SystemWindowFrame, SystemWin- dowText. 3Macintosh ¥§Œ±¦^e¡XÚôÚ: SystemButtonFace, SystemButtonFrame, SystemButtonText, SystemHighlight, Sys- temHighlightText, SystemMenu, SystemMenuActive, SystemMenuActiveText, System- MenuDisabled, SystemMenuText, SystemWindowBody. annCharles@tom.com 1178,208 Python ÆS)P §4.5 Widget ª ôÚ¶¡´Ø©Œ" …k ôÚ¶iŒ±3ücƒm\˜‡˜‚" X”light blue” ”LightBlue” ´˜‡ôÚ" RGB ôڊ „Œ±½RGB n‡©þŠ§5½ôÚ"‚ª´ #RGB,#RRGGBB, #RRRRGGGGBBBB ~X: w["fg"]="#f00" w["fg"]="#ff0000" w["fg"]="#ffff00000000" Ñ´rcµÚU¤ùÚ"RGB n‡©þÑAT´›8?›"e¡{ü~f§`² XÛ˜RGB ©þ" tk_rgb = "#%02x%02x%02x" % (172, 182, 220) tk_rgb = "#%04x%04x%04x" % (172, 182, 220) w.wininfo_rgb() Œ±rôÚ¶¡€È¡ôÚRGB ©þ"X rgb = widget.winfo_rgb("red") red, green, blue = rgb[0]/256, rgb[1]/256, rgb[2]/256 5¿winfo_rgb ˆ£´‰Œ´0 – 65535 §XJ‡0 – 256 ‰ŒSŠ§‡Ø ±256 ⌱§Ò´m£8  " §4.5.2 iN Tkinter ¥widget #N^r½iN"˜„ØI‡½iN§ÏTk ¥Œõê{ üwidget §XLabel §Button §ÑkéÐ%@iN" 3½iNžÿ§^font option §Tkinter Œ±¦^ØӐª£ãiN" • iN£ãÎ(font descriptor ) • ^rg½ÂiN¶¡§¦^tkFont ¬" • XÚiN¶¡ •X iN£ãÎ( X font descriptor) iN£ãÎ(font descriptor) lTk 8.0 m©§Tkinter Œ±¦^ÕáuäNXÚiN£ã§kÏuª²?§"Œ ±ÏL½iNx§iNpݧÚÙ¦˜ ŒÀiNº‚(font style)5½iN"X annCharles@tom.com 1179,208 Python ÆS)P o Tkinter ?§ ("Times", 10, "bold") ("Helvetica", 10, "bold italic") ("Symbol", 8) iNº‚(font style) ´iN´Ø´\o§´Ø´N" XJ==‰Ñ iNx¶¡§@oÒ¬%@iNpݧÚiNº‚" XJiNx¶¡¥Ø¹k˜‚§Œ±==‰Ñ5˜‡iÎG^5£ãiN"„Œ± O\iNpÝÚiNº‚½Â" "Times 10 bold" "Helvetica 10 bold italic" "Symbol 8" 3Windows ¥~^iN): Arial (corresponds to Helvetica), Courier New (Courier), Comic Sans MS, Fixedsys, MS Sans Serif, MS Serif, Symbol, System, Times New Roman (Times), and Verdana: XJiNx¶¢¥¹k˜‚§@oÒ7L^1˜«Lˆª5L«iN" ~^iNº‚k: normal, bold, roman, italic, underline, Úoverstrike. 3ØÓ²þ§Tk 8.0§gÄrù ~^iN§X§Courier, Helvetica, ÚTimes N²iNLˆªþ§ …§XJiNN”}{§¬é˜‡bCi N5“O"¤±3½iNžÿTk 8.0 l5Ñجw†Ø"XJé؁bCi N§@oÒ´^%@iN"´Tk @bCiN§kžÿ¿Ø´\Ž‡§¤±Ø ‡Lõ‚ù‡A5" Windows eTk 4.2 |±ù«iNLˆª" ¦^tkFont Font a5½iN Ø ^iN£ãÎ(font descriptor) £ãiNƒ §„Œ±ÏLtkFont 5½i N"Font ¬¥tkFont a§Œ±^5½iN"?ÛTkinter I‡iNëê§\Ñ Œ±^tkFont 5½"~X: annCharles@tom.com 1180,208 Python ÆS)P §4.5 Widget ª tkFont.Font(family="Times", size=10, weight=tkFont.BOLD) tkFont.Font(family="Helvetica", size=10, weight=tkFont.BOLD, slant=tkFont.ITALIC) tkFont.Font(family="Symbol", size=8) myfont=tkFont.Font(...) ˆ £ ˜ ‡ é –  ‰myfont § @ o Ò Œ ± ^w.config(font=myfont) 5  ½widget w  i N ´myfont ¤ £ ã  i N" ù  k ˜ ‡ Ð? ´ § XJ ¦ ^myfont.config(size=40) § @ o ¤ k ¦ ^myfont Š  i N widget iNÑgč# §âŠ‰font propagate "é¤"ù3§S¥§Œ±‰˜ |aqwidget ½iNmyfont §,‡?U myfont @où˜|widget iNѬ #" tkFont.Font |±option XL4.5-1: Option a. £ã family string iNx¶¡ size integer iNŒ§ü point §XJ´Kê§ü ´pixel weight constant NORMAL „´BOLD §%@´NORMAL. slant constant NORMAL „´ITALIC §%@´NORMAL. underline flag 1 ‘ey‚"0 ؑey‚" overstrike flag 1 ¥mk0¥mؑî‚" L 4.5-1: tkFont |±option XÚiN¶¡ Tk „|±XÚ½ÂiN¶¡§3X Windows e§˜„´iNO¶§Xfixed, 6x10 " Windows e§Œ±´ansi, ansifixed, device, oemfixed, system, and systemfixed" 3Macintosh e§XÚiN¶¡Œ±´application and system" 5¿XÚiN¶¡´iN¡§)iNx¶¡ÚiNŒ§iNº‚"XJlŒ £‡5Ä{§Ð؇¦^ù«ª" X Font Descriptor X Font Descriptor ´¦^e¡‚ªiÎG"(ÒL«^%@Š" -*-family-weight-slant-*--*-size-*-*-*-*-charset family L«iNx¶¡" weight Œ±´Bold ½öNormal" annCharles@tom.com 1181,208 Python ÆS)P o Tkinter ?§ slant Œ±´RL«Roman §~"½öIL«N"½öOL«oblique §N˜" size ´L«iNŒ§ü ´point ›©ƒ˜§Ï~72 point = 1 inch charset L«iÎ8§Ï~´ISO8859-1" -*-Times-Bold-R-*--*-120-*-*-*-*-ISO8859-1 L«iN´12 point Œ§\oTimes iN§¦^ISO Latin 1 ?èiÎ8" XJ\Ø'%, Š§@oÒ^(ғO" ˜‡;.X Server ˜„Ñ|±Times, Helvetica, Courier, iN§Œ´8 , 10 , 12, 14, 18 , 24 . Œ±´\o§N"Œ±¦^xlsfonts Úxfontsel Unix ·-5w«iN" Windows ÚMacintosh |±ŒÜ©ù iN§¦‚¬rù«Lˆª€È¤Windows e½Macintosh Ü·iN" §4.5.3 ©i‚ªz ˜„5`§Label ÚButton Ø=|±ü1©i§„|±õ1©i"õ1©iÒ´ ^"\n" ©õ‡ü1©i"%@œ¹e§©i´Ø¥éৌ±UCjustify option LEFT ½öRIGHT L«†½öméà" „Œ±˜wraplength option 5½Œݧ©iÝXJ‡L ù‡ŒÝ ÒgĆ1" §4.5.4 >µ ¦+k Widget>µ3%@œ¹e´wا´¤kWidget Ñk˜‡> µ">µ)3D Relief( 2H) JÚFocus Highlight( :pw)«" relief option ^ 5 L«XÛ ± › ˜ ‡Widget  > µ " Œ ± ´SUNKEN RAISED GROOVE RIDGE ÚFLAT borderwidth ½öbd option L«widget >µŒ§˜ „´2 ½ö1 §Œ ÒØÐw " Focus Highlight Region (:p«)´˜«>µ§´3>µƒ ,˜‡>µ" 3widget Ñ\:žÿ§Ò´widget Œ±É^r…Ñ\¯‡žÿ§±x ù‡Focus Highlight Region §Ò´3>µ ¡2x˜‡>µ§L«ù‡widget  :§Œ±ɅÑ\" highlightcolor option L«widget :žÿ§Focus Highlight Region ôÚ§ ˜„´çÚ"highlightbackground option L«widget vk:žÿ§Focus High- light Region ôÚ§˜„Úwidget ˜µÚ"highlightthickness L«Focus Highlight Region °Ý"˜„´1 ½ö2 §Œ ÒØÐw " ùpk˜‡~f§^5`²>µÚFocus Highlight Region ^{" # border1.py annCharles@tom.com 1182,208 Python ÆS)P §4.5 Widget ª from Tkinter import * bd = range(1,9,3) t = [ "border = " + str(k) for k in bd ] relief= [ RAISED, SUNKEN,GROOVE ,RIDGE,FLAT] for i in range(len(bd)): for j in range(len(relief)) : Button(text=t[i]+" " + relief[j], relief=relief[j], highlightcolor = ’blue’, highlightbackground = ’white’, highlightthickness = bd[i], bd=bd[i]).grid( row=j, column=i, padx=2, sticky=W) mainloop() $1(JXã4-4" ã 4-4: border1.py $1(J annCharles@tom.com 1183,208 Python ÆS)P o Tkinter ?§ highlightcolor Úhighlightbackground ¿‰¤Ø´AOÐwôÚ§4Öö5¿¦ ‚Cz" §4.5.5 àI cursor option Œ±½˜‡àI/G§àI£Äù‡widget þžÿ§w«ù ‡àI/G"XJ؍½ù‡option §@oàI£Äwidget þžÿ§w«Ú¦ master widget cursor option ¤½àI/G" ”Text ÚEntry ùwidget §%@UC àI/G§L«I‡Ñ\©i" e¡ù‡~fü« cursor option J" #!/usr/bin/env python cursors =["arrow", "based_arrow_down", "based_arrow_up", "boat", "bogosity", "bottom_left_corner", "bottom_right_corner", "bottom_side", "bottom_tee", "box_spiral", "center_ptr", "circle", "clock", "coffee_mug", "cross", "cross_reverse", "crosshair", "diamond_cross", "dot", "dotbox", "double_arrow", "draft_large", "draft_small", "draped_box", "exchange", "fleur", "gobbler", "gumby", "hand1", "hand2", "heart", "icon", "iron_cross", "left_ptr", "left_side", "left_tee", "leftbutton", "ll_angle", "lr_angle", "man", "middlebutton", "mouse", "pencil", "pirate", "plus", "question_arrow", "right_ptr", "right_side", "right_tee", "rightbutton", "rtl_logo", "sailboat", "sb_down_arrow", "sb_h_double_arrow", "sb_left_arrow", "sb_right_arrow", "sb_up_arrow", "sb_v_double_arrow", "shuttle", "sizing", "spider", "spraycan", "star", "target", "tcross", "top_left_arrow", "top_left_corner", "top_right_corner", "top_side", "top_tee", "trek", "ul_angle", "umbrella", "ur_angle", "watch", "xterm"] from Tkinter import * root = Tk() col=0; row = 0 for i in cursors: b=Button(text=i) b.grid( column=col,row=row, sticky=E+S+W+N) b.bind("",lambda e,cur=i:root.config(cursor=cur)) col = col + 1 if col == 4 : row = row + 1 ; col = 0 annCharles@tom.com 1184,208 Python ÆS)P §4.5 Widget ª mainloop() $1(JXã4-5" ã 4-5: cursor1.py $1(J àI£Ä z˜‡ØÓUÜþ§àI/GÒ¬C¤ØÓ/G" annCharles@tom.com 1185,208 Python ÆS)P o Tkinter ?§ §4.6 ¯‡Ú¯‡½ Ÿo´¯‡§^rŒU£ÄàI§½öU ˜‡…§ù Ñ´¯‡§¯‡„)WM ‡¦widget ­xgC¯‡"éõwidget ь±ɯ‡§¿…N^ƒA?n¼ê"ò ¯‡Ú´¯‡?n¼êéX˜å{Ò´N^ w.bind(event,handler) w ´˜‡widget, event ´˜‡iÎG§^uL㯇§handler ´˜‡callable é –§^u?n¯‡§Ò´`§3¯‡u)žÿ§¬N^ù‡é–§Óž¬D4˜‡ë ê§^u£ã¯‡" §4.6.1 ˜‡{ü~f # File: bind1.py from Tkinter import * root = Tk() def callback(event): print "clicked at", event.x, event.y def test(e): D = vars(e); for k in D: print "%-10s:%s"%(k,D[k]) frame = Frame(root, width=100, height=100) frame.bind("", callback) root.bind("",test); frame.pack(expand=1,fill=BOTH) frame.focus_set() root.mainloop() ù‡§SrüÂàI†…¯‡Úcallback ù‡¼ê”½3˜å§”½¿gÒ´` )ù‡,‡¯‡žÿ§ÒN^ƒA?n¼ê" XJ,‡¯‡u) §Óž‰1 ƒA?n¼ê§·‚¡Ó¼ ù‡¯‡" $1ù‡§S§XJ3Frame þüÂàI§Ò¬3››þ‹<àI‹I"XJÓ žUeControl §Alt §ÚkÒ§Ò¬‹<¯‡¤k&E" £ã¯‡ª þ˜‡~f¥§”¡Button-1¿” £ãàIü†…¯‡§£ã¯‡‚ªXe: annCharles@tom.com 1186,208 Python ÆS)P §4.6 ¯‡Ú¯‡½ 0 àI…½Â3X windows ¥˜k5 ‡àI…½Â§˜„´ 1 †… 2 ¥… 3 m… 4 E¶þE 5 E¶eE ˜„^1 , 2 , 3 n‡…" ´Ø´˜¤ØC§Œ±^xmodmap ·-UC" xmodmap -pp Œ±wcàIU…½Â" 3wu)Ÿo¯‡žÿ§±eóä´ék^" xmodmap wÚ?UX …N'XÚàIN'X" xev ^5w¯‡" modifier L«u)àI½ö…¯‡žÿ§ÓžUe Ù¦…§Xcontrol §alt §win(super) …§½ö˜‡¯‡3ážmS­Eõg" modifier Œ±´ Control Mod2, M2 Shift Mod3, M3 Lock Mod4, M4 Button1, B1 Mod5, M5 Button2, B2 Meta, M Button3, B3 Alt Button4, B4 Double Button5, B5 Triple Mod1, M1 Quadruple B1 L«u)…¯‡žÿ§àI†…´?uUeG" Meta ÚAlt Ñ´Œ±ÏLxmodmap UCN'X"äN´=˜‡…ÚXXÚ˜ k'X" Œ±½õ‡modifier §^~Ò©"X Ù¥Control §Alt ´modifier §Key ´type §colon ´detail §‡¯‡£ãL«Óž UeControl Alt ÚkÒ§Ò´`ӞUeControl Alt Shift کҧϏӞUeShift Ú©Ò§L«kÒ" Double ^u£ãàIV¯‡" type ´  ­ ‡  § § ½  · ‚ ” ½ = ˜ « ¯ ‡ " ˜ „ ´ButtonPress §ButtonRelease ½ö´KeyPress §KeyRelease §Œ±´Ù¦Š§Œ±ÏL annCharles@tom.com 1187,208 Python ÆS)P o Tkinter ?§ man -S n bind w¤k¯‡a." type ´ButtonPress ÚButton Release žÿ§detail Œ±´1, 2, 3, 4, 5 ^uL«à I…§XJ؍½detail §L«U?ۅ" 5¿àIU…Šmodifier Útype «O§Ò´ Ú «O" cöL«,«¯‡u)žÿ§àI,‡U…?3UeG"öL«u) àIU …¯‡" type ´Motion  ž ÿ § L« à I £ Ä ¯ ‡ " ˜ „  ½B1 modifier" X L«àI†…Ue¿…£ÄàI"XJ؍½modifier §@oL«¤k àI£Ä¯‡" XJtype ´KeyPress ½öKeyRelease §@odetail ^5½.´=˜‡…U…" äNŠŒ±wkeysyms Ï" man keysyms keysyms ´˜‡Œ‹<ASCII iΧ½ö˜‡ØŒ‹<ASCII iΣ㧄 Œ±´šASCII iΣã" ü‡k^ "<1> <2> <3> ©OL«àI†…§¥…§m…U…¯‡" ... L«Uea, b, c iί‡" ¯‡£ãÞ~§XL4.6-2µ §4.6.2 ¯‡?n¼ê u)¯‡žÿ§¬N^¯‡?n¼ê§D4˜‡ëêevent §^u£ã¯‡u) žÿ&E"^e¡“茱‹<¤k&E" def test(event): D = vars(event); for k in D: print "%-10s:%s"%(k,D[k]) äNëêXeL4.6-3 §4.6.3 ¯‡g Ә‡¯‡Œ±kõ‡¯‡?n¼ê§ù ?n¼êáuØÓg"z˜‡g„Œ ±kõ‡¯‡?n¼ê?nӘ‡¯‡" Œ±3o‡ØÓg¥”½¯‡" • widget instance ? ½,˜‡widget instance ¯‡”½"k3¯‡u)3,˜‡½widget ž ÿ§â¬Ó¼¯‡"”½{´w.bind(...) §w ´˜‡widget instance " annCharles@tom.com 1188,208 Python ÆS)P §4.6 ¯‡Ú¯‡½ ½<1> UeàI†… UeàI†…Óž£ÄàI" º˜àI†…" 3éážmS(š~¯„)§àI£Ä3é ‰ŒS(Avk£Ä)§ëYUeügàI†…" àI£Ä Widget ‰ŒƒS"5¿Ø´Ue …£…§Enter L«¯‡type " àIlmWidget ‰ŒƒS" U e …   £  … " ´ ˜ ‡ {  § L « "3keysyms Ï¥Œ± A¤kš‹ Ue ?Û…" a L«Ue …“a” …" L«U4…Shift …ؘӞ§Ue •…¥ þ…" L«Widget Œu)UCžÿ¯‡" L 4.6-2: ¯‡£ãÞ~ widget )¯‡widget §¤k¯‡event Ѭ˜ù‡ á5" x,y L«u)¯‡žÿ§àI3widget ¥ƒé ˜" ü ´pixel x root, y root L«àI3¶4¥ƒé ˜" char a.´string §L«Ú…k'¯‡¥§äNUe ´=˜‡iÎè" keysym 3څk'¯‡¥§L«U…©i£ã" num 3ÚàIk'¯‡¥§L«àIU…" wight, height L«widget #Œ"3configure ¯‡¥k" type L«¯‡a." L 4.6-3: £ã¯‡ëê annCharles@tom.com 1189,208 Python ÆS)P o Tkinter ?§ • I? widget ¤ á Toplevel é – ½ öroot é – § ½ ö ` I  ? §  ” ½  { ´root.bind(...) ½ötop.bind(...) root Útop ©OL«Toplevel é–Úroot é –" • widget class ? ¦^bind_class §L«¤k½class instance Ѭk˜‡¯‡”½" • A^§S? ?Û/u)¯‡§Ñ¬Ó¼"¦^bind_all " ~X¦^bind_all ”½F1 …§ùÃØ3?Û/§‡U F1 …Ò¬‰1Ï§ S" ´XJӘ‡¯‡3ØÓgþ”ºõgžÿ§TNoQ? ½ö`˜‡¯‡­ U”½žÿ§TNoºŸo´­U”½Qº~X§·Óž”½ Ú ¯‡§˜‡L«Ue?¿…§˜‡L«Ue£…¯‡§ ¯‡Óž´˜ ‡ ¯‡§ùÒ´­U”½" Äk§˜‡¯‡u)žÿ§Tkinter 3z˜‡gþ§Ï阇ƒC¯‡” ½"~X§XJUe £…§ ¯‡' ¯‡C" ¯‡¬Ó ¼§ ¯‡KجÓ¼" Ò´`§­U¯‡ƒü½§C¯‡Ó¼" ^aqêÆŠó£ãÒ´§z˜‡¯‡£ãј‡¯‡8ܧ8Ü¥ƒ´˜ ‡¯‡§XJ˜‡8ÜA ´,˜‡8ÜB f8§@o`ù‡A'B "¯‡u)ž ÿ§@oÒ3z˜‡gþÏ靹T¯‡8ܧ,2z˜‡gþÓ¼T¯‡" XJ3widget instance g”½ ¯‡§3toplevel þ”½ ¯‡§ @oUe£…žÿ§ù‡¯‡3ü‡gþѬÓ¼" ù´Ïùü‡¯‡Ø´­U¯‡§ ´3ØÓgþ¯‡§­U¯‡´½Â3Ә gþVg§Ò´`§­U¯‡Ñ´3Әgþ" Tkinter Äk3widget instance gþÓ¼¯‡§‰1¯‡?n¼ê§,g 3widget class gþ§Toplevel gþ§A^§S?þ§©OÓ¼¯‡"ù‡Ó¼¯ ‡^S魇" Ò´`§ØÓgþ¯‡U^SÓ¼" §Sbind level.py éÐ`² ù˜:" # File: bind_level.py from Tkinter import * root = Tk() def callback(event): annCharles@tom.com 1190,208 Python ÆS)P §4.6 ¯‡Ú¯‡½ print "clicked at", event.x, event.y def test(e): print "you press: " + e.keysym return def application_level_bind(e): print "application level binding" test(e) def class_level_bind(e): print "class level bind " test(e) def toplevel_bind(e): print "top level bind" test(e) def widget_level_bind(e): print "widget instance level bind" test(e) def myprint(a): print a frame = Frame(root, width=100, height=100) root.bind("", toplevel_bind) root.bind_class("Frame","",class_level_bind) root.bind_all("",application_level_bind) frame.bind("", widget_level_bind) frame.bind("", lambda e: myprint("RETURN PRESSED") ) frame.pack(expand=1,fill=BOTH) frame.focus_set() root.mainloop() §4.6.4 Ә‡¯‡õ‡?n¼ê Ә‡¯‡Œ±kü‡±þ¯‡?n¼ê"bind(e,func) ¼ê%@Ċ´^½ ¯‡?n¼êfunc “O¤kk¯‡?n¼ê"´XJ½1n‡ëꏓadd” ~X: bind(e,func,"add") Ҍ±35¯‡?n¼ê§Ò´3˜‡¯‡?n¼êóO\˜‡?n¼ê" ˜‡¯‡u)žÿ§Ò¬d‰1¯‡?n¼êóþz˜‡¯‡?n¼ê"XJ=˜ ‡¼êˆ£ ˜‡iÎG“break” @oҬʎ‰1¡¯‡?n¼ê§ÓžÊŽN^ annCharles@tom.com 1191,208 Python ÆS)P o Tkinter ?§ Ù¦g¯‡?n¼ê" ~fchange text bind.py `² ù‡¯K" # change_text_bind.py from Tkinter import * def ignore (e): return "break" def ignore2(e): print "you can only input one line" root = Tk() t = Text() t.bind("",ignore2) t.bind("",ignore,"add") t.pack(fill=BOTH,expand=1) root.mainloop() ù‡~fŽ?U˜‡Text widget %@¯‡”½§3%@œ¹e§Ue£…L« Ñ\#˜1§XJ==”½ignore2 ´Ø1§¦+O“ instance ?Oþ”½'X§ ´ ¯‡?n´class ?Oþ§¤±„Øv±UC%@öŠ§^r„´Œ±Ñ \#˜1"¤±O\ignore ”½§4¦ƒä¯‡?n¼êUY‰1§ùâUˆ8 ",§3ignore2 ¥ˆ£“break” ´Œ±" XJ¯‡?n¼êó¥k˜‡¼êˆ£ “break” @o2O\?n¼ê´vk¿Â" „k˜«{Œ±‰§ root.bind_class("Text"," /*7L‡\\Þ©‡*/ static PyObject * /*¤kPythoné–Ñ´ù‡a..*/ spam_system(PyObject * self, PyObject * args) { char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); } static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "Execute a shell command."}, {NULL, NULL, 0, NULL} /* L«L‚(å */ }; void initspam(void) { annCharles@tom.com 1205,208 Python ÆS)P Ê Python*Ð Py_InitModule("spam", SpamMethods); } ·‚F"ïᘇmodule ¶iŠspam§·Œ±ÏLspam.system(cmd) ª§¤ Úos.systemaqóŠ" Äk©Û˜eù‡§S§˜kü‡¼ê§initspam(...) §spam_system(...) §˜‡ÛCþ§SpamMethords "initspam´¬Ð©z¼ê§importžÿ¬N ^§§´˜š·¼ê"¶i´init + module_name/ª§·‚module  ‰spam"¦ƒumain ¼ê"¦̇?Ö´Ïpython )ºì§·‚spam ¥kõ ‡¼ê"Py_InitModule Ò´Zù‡¯œ"1˜‡ëê´"spam" §L«module  ¶¡"1‡ëê´SpamMethords ´˜‡L‚§Ïpython §·‚spam kõ‡¼ ê"SpamMethors ˜½‡´Û·Cþ§a.´PyMethodDef" PyMethordDef ±˜L«L‚(å"z˜1ko‡iãµ • 1 ˜ ‡ L«python ¥ ¼ ê  ¶ i § ù p ´ system§ 3python ¥ Œ ± Ï Lspam.system 5N^ù‡¼ê" • 1‡i㴘‡¼ê§spam_system§ù‡¼ê.˜½‡´ static PyObject * spam_system(PyObject * self, PyObject * args);  ÚMETH_VARARGSƒéA" • 1n‡iã´doc string§3python ¥Œ±ÏLspam.system.__doc__ " •  ˜ i ã ´ ˜ ‡ ÷(macro) § L« ¼ ê a ." lCŠ ó  *: 5 w §Python ¥  ¼ ê k ü « § ˜ « ´ ~ ^  ^tuple 5 D 4 ë ê § ˜ „ ´METH_VARARGSL«§˜«´^dictionary 5D4ë꧉ keyword parameter§ ^METH_VARARGS|METH_KEYWORDSL«"ùü‡Macro Ò©OéAùü«¼ê"ü« ª3C Šó¥éA¼ê.´Ø˜" w w · ‚ ý  Z ¹  ¼ êspam_system§ ¦  ˆ £ Š L«Python ¥ ¼ ê  ˆ £ Š §“˜ ƒ Ñ ´ é –” ù é { 3C Š ó ¥  L y / ª Ò ´PyObject* § ˜ ƒ Ñ ´PyObject*"XJц§@o3C Šó¥k¼ê§Œ±^5ÑÉ~§ˆ£ŠÒ´NULL " spam_systemëêkü‡§w¦‚a.´PyObject*Ҙ:ØÛ% j" • self ˜„Ø^§XJ´ØÓ¼ê{§¦o´NULL§XJ¦´˜‡class methord {§self L«class instance" • argsL«D?5ë꧴˜‡tuple §5¿tuple 3CS܏´PyObject* annCharles@tom.com 1206,208 Python ÆS)P §5.1 ^C?*Ь PyArg_ParseTuple^5ëê"Ù¥args ´D?5ëê""s"L«‚ª=†a .iÎG§sL«string a.§„kÙ§a."¡ëê҇Ú"s"¤½a.ƒ·A" Ú"s"ƒ·Aa.´char**§´˜‡i΍"Ò´`§Ø^·‚gC5? S+n¼ê§XJPython¥XÚ¼êPyArg_ParseTuple~ˆ£§@ocommandҍ •˜‡kiÎG"XJ´”}§@o҈£NULL"PyArg_ParseTuple ”}žÿ§ ¦¬gÄÑÉ~§Ø^·‚gC3?ÑÉ~“è"ùwÑÉ~śÐ?" e¡Ò´N^system §ù ÚC Šó?§vkŸoü"·‚rsystemˆ£Š sts Š·‚¼êˆ£Š"Py_BuildValue()´^5Mpython é–^§ˆ£ ˜‡PyObject* §¦1˜‡ëê^5²é–a.""i"L«integer"¡ëêÚë êa.ƒ˜—"ÄK¬ÑÉ~§ˆ£NULL" ·uy*ÐPython '^Python ?§I‡Jõ§Ò”?°Ä§S‡'ÊÏA^§ SJ§ÏØ‡éXÚN^ )§„‡éöŠXÚSÜk )"*ÐPython ´˜ §I‡éPython ¢yśk¤ )"Ð §y3·‚‡)¤·‚module "^C Š ómodule ´kü«{\Python ¥"˜«´r†ÚPython  “è˜å?È" 3Unix²e§é{ü§‡3Modules/Setup.local¥\þ˜1§ spam spammodule.o ,§rspammodule"c €Modules 8¹e¡ÒŒ± "­#?ÈPython "ù‡{ kw ´„":§­#?ÈPython ŒvkŸoÐ " 1‡{§rC §S?ȤÄë¥"´k‡¯K§ØÓ²eéÄë ¥|±ª´Ø˜§«OéŒ"3Ч·‚k˜‡distutils package Œ±· ‚‰ù‡¯œ"?˜‡setup.py ©‡§©‡SNXe" $ls setup.py spammodule.c $cat setup.py from distutils.core import setup, Extension module1 = Extension(’spam’, sources = [’spammodule.c’]) setup (name = ’spam package’, version = ’1.0’, description = ’This is a spam package’, ext_modules = [module1]) äN¿g§Œ±ëdistulis Ãþ" $python setup.py build #?È running build running build_ext annCharles@tom.com 1207,208 Python ÆS)P Ê Python*Ð building ’spam’ extension creating build creating build/temp.linux-i686-2.2 gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC \ -I/usr/include/python2.2 -c spammodule.c \ -o build/temp.linux-i686-2.2/spammodule.o creating build/lib.linux-i686-2.2 gcc -shared build/temp.linux-i686-2.2/spammodule.o \ -o build/lib.linux-i686-2.2/spam.so $ $ls #õ ˜‡build f8¹ build setup.py spammodule.c $cp build/lib.linux-i686-2.2/spam.so . #€c8¹ $python #$1python )ºì Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import spam #Ú\·‚ module >>> print spam.system.__doc__ #w DOC string Execute a shell command. >>> print spam.system("echo ’hello’") #ww¤õ íº hello #ok,~ÑÑ 0 # spam.system ˆ£Š >>> annCharles@tom.com 1208,208 Python ÆS)P
还剩217页未读

继续阅读

pdf贡献者

b2df

贡献于2015-08-30

下载需要 8 金币 [金币充值 ]
亲,您也可以通过 分享原创pdf 来获得金币奖励!