Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this document? Why not share!

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
993
On Slideshare
993
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
6
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. PythonLeafWang@163bj.com or AnnCharles@tom.com 2003 08 26
  • 2. annCharles@tom.com 2 , 152 Python
  • 3. Python 1 §1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 §1.1.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 §1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 §1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 §1.3.1 (integer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 §1.3.2 (float) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 §1.3.3 None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 §1.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 §1.4 (list) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 §1.4.1 list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 §1.4.2 list list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 §1.4.3 list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 §1.4.4 list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 §1.4.5 list . . . . . . . . . . . . . . . . . . . . . . . 10 §1.4.6 list comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 §1.5 (string) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 §1.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 §1.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 §1.5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 §1.6 (tuple) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 §1.7 (sequence) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 §1.8 (dictionary) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 §1.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 §1.8.2 dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 §1.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 §1.9.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 §1.9.2 for while break continue range() . . . . . . . . . . . . . 29annCharles@tom.com i , 152 Python
  • 4. §1.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 §1.10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 §1.10.2 . . . . . . . . . . . . . . . . . . . . . . 33 §1.10.3 . . . . . . . . . . . . . . . . . . . . . . . . . . 34 §1.10.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 §1.10.5 Doc String . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 §1.10.6 lambda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 §1.10.7 (scope) . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 §1.10.8 (nested) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 §1.10.9 function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 §1.11 (module) (package) . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 §1.11.1 module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 §1.11.2 module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 §1.11.3 package( ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 §1.12 name space( ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 §1.13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 §1.13.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 §1.13.2 (method) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 §1.13.3 (property) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 §1.13.4 (inherit) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 §1.13.5 (overload) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 §1.13.6 class attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 §1.13.7 Abstrace Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 §1.13.8 Python . . . . . . . . . . . . . . . . . . . . . . . . . . 50 §1.13.9 Python class methord . . . . . . . . . . . . . . . . . . . . . 50 §1.14 (exception) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 §1.14.1 . . . . . . . . . . . . . . . . . 57 §1.14.2 exception( ) . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 §1.14.3 exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Python 66 §2.1 Emacs Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 66annCharles@tom.com ii , 152 Python
  • 5. §2.1.1 python mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 §2.1.2 python mode . . . . . . . . . . . . . . . . . . . . . . . . . 67 §2.1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 §2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 §2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 §2.3.1 DDD pydb python . . . . . . . . . . . . . . . . . . . . 70 Python 71 §3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 §3.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 §3.1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 §3.1.3 . . . . . . . . . . . . . . . . . . . . . . . . . 75 §3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 §3.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 §3.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 §3.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 §3.3 regular expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 §3.3.1 regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 §3.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 §3.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 §3.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 §3.3.5 re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 §3.3.6 regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 §3.3.7 (Group) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 §3.3.8 Compile Flag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 §3.4 struct . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 §3.5 Cmd . . . . . . . . . . . . . . . . . . . . . . . . 93 §3.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 §3.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 §3.5.3 EOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 §3.5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 §3.5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96annCharles@tom.com iii , 152 Python
  • 6. §3.5.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 §3.5.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 §3.5.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 §3.5.9 Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 §3.5.10 getattr . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 §3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 §3.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 §3.6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 §3.6.3 optparser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 §3.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Tkinter 111 §4.1 Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 §4.1.1 Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 §4.2 Hello Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 §4.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 §4.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 §4.3 Widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 §4.4 Geometry Manager( ) . . . . . . . . . . . . . . . . . . . . . . . . . 116 §4.4.1 Pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 §4.4.2 Grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 §4.5 Widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 §4.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 §4.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 §4.5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 §4.5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 §4.5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 §4.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 §4.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 §4.6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 §4.6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 §4.6.4 . . . . . . . . . . . . . . . . . . . . . . . . 135annCharles@tom.com iv , 152 Python
  • 7. §4.6.5 WM . . . . . . . . . . . . . . . . . . . . . . . . . . 136 §4.7 Widget . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 §4.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 §4.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 §4.7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 §4.7.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 §4.7.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Python 149 §5.1 C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149annCharles@tom.com v , 152 Python
  • 8. 1.5-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.5-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.5-3 . . . . . . . . . . . . . . . . . . . . . . 16 3.1-1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 3.1-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 3.2-3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 3.4-4 struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 3.4-5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 3.5-6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 3.7-7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 4.5-1 tkFont option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 4.6-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 4.6-3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133annCharles@tom.com vi , 152 Python
  • 9. Pythonpython python eval VB Script Engi- neer Lisp EVAL Emacs Python (class) (function) (module) Java C++ OO( Object Oriented) “ OO? Java OO?” Python Python C C C++ Python Python C C++ Python VIM Emacs Python (declare) VB VB Script JScript PERL (declare) string integer VB VBScript JScript PERL JavaannCharles@tom.com 1 , 152 Python
  • 10. Python§1.1§1.1.1 Python Python Perl VB Bash Awk Sed • Unix $ $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 >>> # CTRL+D Windows >>> ... Python Bash C-a C-e C-w readline • python $cat test.py print "Hello World" $python test.py Hello World $cat test.py | python # Hello World $python < test.py # Hello World • Unix $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.pyannCharles@tom.com 2 , 152 Python
  • 11. §1.2 -rwxr-xr-x 1 chunywan mnw 40 Sep 12 13:34 test.py $./test.py Hello World Unix Perl Tl/Tcl Sed awk Bash # bash§1.2 (class) (function) (module) “ ”§1.3§1.3.1 (integer) + 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 (float) 1 1.0 1 == 1.0§1.3.3 None None§1.3.4 Python boolean C 0 Python “ ”annCharles@tom.com 3 , 152 Python
  • 12. PythonNone,0,0.0,"" ( ),[]( list),()( tuple),{}( dictionary) Python and or not>>> 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 # getTruedebug: false # getTrue , getFalsebad # getFalse .>>> if getFalse() and getTrue():... print "ok"... else:... print "bad"...debug: false # getFalsebad # getFalse , getTrue>>> and or and expr1 and expr2 expr1 expr1 list expr2 expr2 expr1 expr2 expr2 or expr1 or expr2 expr1 expr1 expr2 expr2 expr1 expr2 expr2 :annCharles@tom.com 4 , 152 Python
  • 13. §1.3<cond> and <expr_true> or <expr_false> : cond expr_true expr_false : cond expr_true expr_false ( ) expr_true ( ) expr_false ( ) expr_false expr_false expr_false : • cond expr_true • cond expr_false • expr_true cond expr_false : (<cond> and (<expr_true>,) or (<expr_false>,))[0] [0] tuple (<expr_true>,) tuple [0] expr_true expr_false >>> x= cond and "OK" or "BAD" >>> x ’OK’ >>> cond = 0 >>> x= cond and "OK" or "BAD" >>> x ’BAD’ >>> :<cond> or <expr_false> and <expr_true> “ ”annCharles@tom.com 5 , 152 Python
  • 14. Python “ ” “ ” C Ccond ? true_expr: false_expr C§1.4 (list) list C++ vector C[ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ][ ’January’, ’February’, ’March’, ’April’, ’May’, ’June’, ’July’, ’August’, ’September’, ’October’, ’November’, ’December’ ][ ’Monday’,’Tuesday’, ’Wednesday’, ’Thursday’ , ’Friday’, ’Saturday’, ’Sunday’]§1.4.1 lista=[’1’,’2’] [] list§1.4.2 list list list 0 C -len ... ... -2 -1 0 1 ... ... len-1>>> a=[0,1,2,3,4,5,6]annCharles@tom.com 6 , 152 Python
  • 15. §1.4 (list)>>> i=-len(a)>>> while i < len(a):... print "a[",i,"]=",a[i]... i=i+1...a[ -7 ]= 0a[ -6 ]= 1a[ -5 ]= 2a[ -4 ]= 3a[ -3 ]= 4a[ -2 ]= 5a[ -1 ]= 6a[ 0 ]= 0a[ 1 ]= 1a[ 2 ]= 2a[ 3 ]= 3a[ 4 ]= 4a[ 5 ]= 5a[ 6 ]= 6 while a[-8] a[9]>>> a[-8]Traceback (most recent call last): File "<stdin>", line 1, in ?IndexError: list index out of range>>> a[7]Traceback (most recent call last): File "<stdin>", line 1, in ?IndexError: list index out of range§1.4.3 list list 0 −1 list>>> a[1:4]annCharles@tom.com 7 , 152 Python
  • 16. Python[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] list list list list§1.4.4 list • L.append(var) >>> a=[0,1,2,3,4,5] >>> a.append(6) >>> a [0, 1, 2, 3, 4, 5, 6] >>> • L.count(var) var L >>> 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) list L >>> a=[1,2,3] >>> a.extend([4,5,6])annCharles@tom.com 8 , 152 Python
  • 17. §1.4 (list) >>> a [1, 2, 3, 4, 5, 6] • L.index(var) var L >>> a=[1,2,3,4,4,5] >>> a.index(4) 3 >>> a.index(6) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: list.index(x): x not in list • L.insert(index,var) index var index list index 0 >>> 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 >>> a=[0,1,2,3,] >>> a.pop() 3 >>> a.pop(0) 0 >>> a [1, 2] >>> • L.remove(var) varannCharles@tom.com 9 , 152 Python
  • 18. Python >>> 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() L >>> a=[1,2,3,4,5] >>> a.reverse() >>> a [5, 4, 3, 2, 1] • L.sort() a a list ? >>> a.sort() >>> a [1, 2, 3, 4, 5] >>> a=[1,"abc",2,"xxx"] >>> a.sort() >>> a [1, 2, ’abc’, ’xxx’] L.sort(func) func func(x,y) −1 0 1§1.4.5 list list stack>>> a=[]>>> a.append(0) #>>> a.append(1)>>> a.append(2)>>> a[0, 1, 2]>>> a.pop() #2annCharles@tom.com 10 , 152 Python
  • 19. §1.4 (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)3annCharles@tom.com 11 , 152 Python
  • 20. Python 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 : [ <expr1> for k in L if <expr2> ] : returnList=[] for k in L: if <expr2>: returnList.append(<expr1>) return returnList; list list expr1 if>>> a=["123","456","abc","Abc","AAA"]>>> [ k.center(9) for k in a ][’ 123 ’, ’ 456 ’, ’ abc ’, ’ Abc ’, ’ AAA ’]# a>>> [ k.upper() for k in a if k.isalpha() ][’ABC’, ’ABC’, ’AAA’]# a>>> [ k.lower() for k in a if k.isupper() ][’aaa’]# a>>> [ int(k) for k in a if k.isdigit() ][123, 456] (filter) (mapping)annCharles@tom.com 12 , 152 Python
  • 21. §1.5 (string) “ list ” : “ list list list ” list 1[ k+1 for k in list] list[ k for k in list if type(k)==types.IntType] list[ k + 1 for k in list if type(k)==types.IntType ]§1.5 (string)§1.5.1’hello’"world" 1.5-1 C echo Java"abc" ’def’ “abcdef” "abc"+"def" +"""this is a very very long string.And it contains a lot line.it is suitable to write document of function."""annCharles@tom.com 13 , 152 Python
  • 22. Python newline ’ ’ " " a 0x07 ASCII b 0x08 ASCII f 0x0c Formfeed (FF) ASCII n 0x0a ASCII N{name} Unicode Unicode r 0x0d ASCII t 0x09 v 0x0b u{xxxx} Unicode Unicode ooo 0xooo ooo xhh 0xhh hh 1.5-1: float(str) float("1e-1") 0.1 int(str) int("12") 12 int(str,base) base int("11",2) 2 long(str) int("12") 12 long(str,base) base int("11",2) 2 1.5-2:§1.5.2§1.5.3>>> "Hello" + " " + "World"’Hello World’>>> "this is test".capitalize() #annCharles@tom.com 14 , 152 Python
  • 23. §1.5 (string)’This is test’>>> "THIS IS TEST".capitalize()’This is test’>>> "THIS IS TEST".lower() #’this is test’>>> "this is test".upper() #’THIS IS TEST’>>> "This Is Test".swapcase() #’tHIS iS tEST’>>> len("Hello World")11 list list 0>>> str="Hello World">>> str="Hello">>> i=-len(str)>>> while i < len(str):... print "str[",i,"]=",str[i]... i=i+1...str[ -5 ]= Hstr[ -4 ]= estr[ -3 ]= lstr[ -2 ]= lstr[ -1 ]= ostr[ 0 ]= Hstr[ 1 ]= estr[ 2 ]= lstr[ 3 ]= lstr[ 4 ]= o>>> -1 0annCharles@tom.com 15 , 152 Python
  • 24. Python>>> str="Hello">>> str[:]’Hello’>>> str[1:2]’e’>>> str[1:-1]’ell’>>> str[-1:2]’’ −1 2 str[-1:2] :>>> a="abcd">>> b=a[1:2]>>> b="x" # b>>> a’abcd’ # a>>> a[1]=’abc’ #Traceback (most recent call last): File "<stdin>", line 1, in ?TypeError: object doesn’t support item assignment>>> 1.5-3 1 0 s.isalnum() 0123456789 A-Z a-z s.isalpha() a-z A-Z s.isdigit() 0123456789 s.islower() a-z s.isupper() A-Z s.istitle() title s.isspace() n,t,r,’ ’ 1.5-3:annCharles@tom.com 16 , 152 Python
  • 25. §1.5 (string) • s.find(substring,[start [,end]]) −1 #ok abc a 3, >>> "ok abc abc abc".find("abc") 3 # 4 s[4:].find("abc") >>> "ok abc abc abc".find("abc",4) 7 # s[4:9].find("abc") >>> "ok abc abc abc".find("abc",4,9) -1 # s[4:10].find("abc") >>> "ok abc abc abc".find("abc",4,10) 7 • s.rfind(substring,[start [,end]]) find() >>> "ok abc abc abc".rfind("abc") 11 • s.index(substring,[start [,end]] find() substring ValueError >>> "ok abc abc abc".index("abc") 3 >>> "ok abc abc abc".index("abcd") Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: substring not found in string.index • s.rindex(substring,[start [,end]] s.index() • s.count(substring,[start [,end]]) substring >>> "ok abc abc abc".count("abc") 3annCharles@tom.com 17 , 152 Python
  • 26. Python s % <tuple> tuple C printf tuple s>>> print "%s’s height is %dcm"%("Charles",180)Charles’s height is 180cm %s,%d C printf conversion specifier ( ) conversion specifier conversion specifier%[<mapping key>][<conversion flag>][<Minimum field width>]|[<precision>][<lenght modifier>]<conversion type>| % conversion type conversion type : • d >>> "%d and %d" % (-1,2) -1 and 2 • i d • o >>> "%o and %o" % (16,8) 20 and 10 • u >>> "%u and %u" %(-10,10) ’4294967286 and 10’ −10 1 • x ( ) >>> "%x and %x" % (100,200) ’64 and c8’ • X ( ) >>> "%X and %X" % (100,200) ’64 and C8’annCharles@tom.com 18 , 152 Python
  • 27. §1.5 (string) • e ( ) >>> "%e and %e"%(-100,200) 2.000000e+02 • E ( ) >>> "%E and %E"%(-100,200) 2.000000E+02 • f >>> "%f and %f"%(-0.00001,200.0) ’-0.000010 and 200.000000’ • g 0.0001 >>> "%g and %g"%(-0.00001,2000000.0) ’-1e-05 and 2e+06’ • c ASCII >>> "%c and %c"%(67,68) ’C and D’ ASCII • r repr() >>> "%r"%({"one":1,"two":2}) "{’two’: 2, ’one’: 1}" print expr(obj) • s str() >>> "%s"%({"one":1,"two":2}) "{’two’: 2, ’one’: 1}" print str(obj) str expr str expr Python mapping key dictionary tuple mapping key key dictionary %d %(height) tuple tuple mapping keyannCharles@tom.com 19 , 152 Python
  • 28. Python>>> 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 mapping key locals() locals() local name space ( ) dictionary key value globals() globalname space ( ) name space( )>>> 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>>> print "%10d,%10d"%(1,2) 1, 2 precision>>> print "%10.2f,%10.2f"%(10.123456,20.126456) 10.12, 20.13 conversion flag # alternate form 8 0 0x 0X>>> print "%#x,%#X,%#o" %(16,16,16)0x10,0X10,020 0 0 minimum field width>>> print "%010d,%010d"%(1,2)0000000001,0000000002 - 0 0>>> print "%-010d,%-010d"%(1,2)1 ,2 0 -annCharles@tom.com 20 , 152 Python
  • 29. §1.5 (string)>>> print "% 10d,% 10d,% 10d"%(-1,2,-0) -1, 2, 0 + + ->>> print "%+10d,%+10d,%+10d"%(-1,2,0) -1, +2, +0 lenght modifier • s.ljust(width) s width width s >>> "Hello World".ljust(1) ’Hello World’ >>> "Hello World".ljust(12) ’Hello World ’ >>> "Hello World".ljust(16) ’Hello World ’ • s.rjust(width) >>> "Hello World".rjust(16) ’ Hello World’ >>> "Hello World".rjust(1) ’Hello World’ • s.center(width) s width s width >>> "Hello World".center(1) ’Hello World’ >>> "Hello World".center(16) ’ Hello World ’ • s.lstrip() s.rstrip() s.lstrip() >>> "t a t".lstrip() ’a ’ >>> "t a t".rstrip()annCharles@tom.com 21 , 152 Python
  • 30. Python ’ a’ >>> "t a t".strip() ’a’ python 2.2.3 chars chars s.strip s.strip("t nr") (join) (split) s.join(words) words tuple list join s words>>> "n".join(["Hello","World","Python","Said"])’HellonWorldnPythonnSaid’>>> print "n".join(["Hello","World","Python","Said"])HelloWorldPythonSaid s.split(words) words split join s list>>> "This is a book".split(" ")[’This’, ’is’, ’a’, ’book’]§1.6 (tuple) tuple • tuple list tuple pop remove insert • tuple () a=(0 1 2 3 4) • tuple tuple • tuple >>> a,b=(1,2) >>> print a,b 1 2 >>> t=(1,2) >>> a,b=t >>> print a,b 1 2annCharles@tom.com 22 , 152 Python
  • 31. §1.7 (sequence) >>> a,b=b,a+1 >>> print a,b >>> 2,2 • tuple : (1 ) tuple list§1.7 (sequence) sequence string list tuple • in object 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) • seq[i] • sequence seq[start:end] • + sequence • * sequence "a"*3 aaa (1,2)*3 (1,2,1,2,1,2) • list comprehension§1.8 (dictionary) dictionary pair key value key integer string1 value dictionary key dictionary tuple tuple tuple pair pair key value D[key] value 1 hash cmpannCharles@tom.com 23 , 152 Python
  • 32. Python§1.8.1# dictionary {}# pair pair key value>>> pricelist={"clock":12,"table":100,"xiao":100 }# dictionary value key>>> pricelist["clock"]12>>> del pricelist["clock"]>>> pricelist{’table’: 100, ’xiao’: 100}# dict(L) dictionary# L list L tuple# tuple 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}# key pair>>> pricelist["apple"]=12 #>>> pricelist{’table’: 100, ’apple’: 12, ’xiao’: 100, ’clock’: 12}# key>>> pricelist["appled"]Traceback (most recent call last): File "<stdin>", line 1, in ?KeyError: appled§1.8.2 dictionary a={"one":1,"two":2,"three":3,"four":4} dictionary D.clear()>>> a.clear()>>> a{}annCharles@tom.com 24 , 152 Python
  • 33. §1.8 (dictionary) dictionaryD.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} c=a c a c a b=a.copy() b b aD.get(key) D key D[key] 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) key default None D.get(key) D.get(key,None)annCharles@tom.com 25 , 152 Python
  • 34. PythonD.haskey(key) D key key in D.keys()>>> a{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}>>> print a.has_key("one")1>>> print a.has_key("abc")0D.items() list tuple(pair) tuple key value>>> a{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}>>> a.items()[(’four’, 4), (’three’, 3), (’two’, 2), (’one’, 1)] D.copy() dict(D.items()) copy()D.keys() list D key>>> 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} copy a.copy()D.values() list D value>>> a{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}>>> a.values()[4, 3, 2, 1]annCharles@tom.com 26 , 152 Python
  • 35. §1.9D.update(E) Efor k in E.keys(): D[k]=E[k]>>> 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} dictionary dictionaryD.popitem() pair D>>> 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 "<stdin>", line 1, in ?KeyError: popitem(): dictionary is empty§1.9§1.9.1 ifannCharles@tom.com 27 , 152 Python
  • 36. Pythonif <expr1>: <one_line_statement>if <expr1>: <statement-block>if <expr1: <statement-block>else: <statement-block>if <expr1>: <statement-block>elif <expr2>: <statement-block>elif <expr3>: <statement-block>...else: <statement-block> • if None 0 ""( ) [] ( list) {}( dictionary ) ()( tuple ) • • • Python Pascal begin ... end C { } Python C “{” if tab 4 8 • Python switch elif 2 • else >>> if x>0: 2 switchannCharles@tom.com 28 , 152 Python
  • 37. §1.9 ... 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() forfor x in <sequence>: <statement-block>else: <else-block> • sequence 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 CannCharles@tom.com 29 , 152 Python
  • 38. Python • else a ( break) else-block C for(i=0;i<len;i++){ if(a[i]==100) break; } if(i==len){/*100 not found*/ /*do something*/ } Python >>> a [1, 2, 3, 4] >>> for x in a: ... if x==100: break ... else: ... print "100 not found" ... 100 not found else break else a 100 else break if 3 else if else if x==100 a x not x==100 else • x x a >>> a=[1,2,3,4] >>> for x in a: ... x=x+1 ... >>> x 5 >>> a [1, 2, 3, 4] 3annCharles@tom.com 30 , 152 Python
  • 39. §1.9 x a Dictionary x Dictionary name space >>> D={"one":1,"two":2,"three":3} >>> for x in D: ... D[x] += 1; ... >>> D {’three’: 4, ’two’: 3, ’one’: 2} range() range([start,]stop,[,step]) start stop 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) [] list range() list >>> a [1, 2, 3, 4] >>> for x in range(len(a)): ... a[x]=a[x]+2 ... >>> a [3, 4, 5, 6] >>> while while <expr1>: <block> else: <else-block>annCharles@tom.com 31 , 152 Python
  • 40. Python expr1 block break expr1 else-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 i=i+1§1.10§1.10.1 :def <function_name> ( <parameters_list> ): <code block> : • function_name • parameters_list • code block if whileannCharles@tom.com 32 , 152 Python
  • 41. §1.10 • return :>>> 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 "<stdin>", line 1, in ? File "<stdin>", line 2, in addTypeError: cannot concatenate ’str’ and ’int’ objects>>> myadd=add>>> myadd(1,2)3 “ ” myadd=add function alias§1.10.2 C++ VB Python :>>> def myjoin(str,sep=","):... return sep.join(str)...>>> myjoin(["a","b","c"])’a,b,c’>>> myjoin(["a","b","c"],";")’a;b;c’ sep “ ” sep “ ”>>> def myrange(start=0,stop,step=1):... print stop,start,step...annCharles@tom.com 33 , 152 Python
  • 42. PythonSyntaxError: non-default argument follows default argument§1.10.3>>> def printValues(name,height=170,weight=70):... print("%s’s height is %d cm,"... " his weigth is %d kgn"%(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>>>>>> printValues("Charles",weight=85)Charles’s height is 170 cm, his weigth is 85 kg§1.10.4 C printf()>>> def printf(format,*arg):... print format%arg...>>> printf ("%d is greater than %d",1,2)1 is greater than 2 *arg * tuple printf arg>> def printf(format,*arg):... print type(arg)... print format%arg>>> printf("a",1)<type ’tuple’>annCharles@tom.com 34 , 152 Python
  • 43. §1.10 arg tuple tuple arg dictionary>>> 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 3keyword[Two] is 2keyword[One] is 1 **keyword ** One=1,Two=2,Three=3 dictionary keyword keys ["One","Two","Three"] values [1,2,3] *arg **keyword>>> printf("%d is greater than %d",2,1,Apple="red",One="1")2 is greater than 1keyword[Apple]=redkeyword[One]=1>>> 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 1optional parameter is 2Arbitrary parameter is (’a’, ’b’, ’c’)keywords parameter is {’three’: 3, ’two’: 2, ’one’: 1}annCharles@tom.com 35 , 152 Python
  • 44. Python§1.10.5 Doc String LISP Python __doc__ string __doc__ string __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 thedoc string.>>> pass C {} __doc__>>> print " ".join.__doc__S.join(sequence) -> stringReturn a string which is the concatenation of the strings in thesequence. The separator between elements is S.>>> print range.__doc__range([start,] stop[, step]) -> list of integersReturn a list containing an arithmetic progression ofintegers. 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 of4 elements.§1.10.6 lambda functional programming lambda LISPannCharles@tom.com 36 , 152 Python
  • 45. §1.10 functional programming language functional programming lambda>>> f = lambda a,b: a+b>>> f(1,2)3>>> f("abc","def")’abcdef’ f def f(a,b): return a+b lambda>>> def incfun(a):... return lambda x: x+a...>>> incfun(2)(12)14>>> incfun(2)(13)15>>> incfun(4)(13)17>>>§1.10.7 (scope) LGB python local name space ( ) global name space( ) buildin name space ( ) global>>> a=1>>> def testfun():... a=2... print a...>>> testfun()2>>> a1 testfun() a local name space a global name space a global name spaceannCharles@tom.com 37 , 152 Python
  • 46. Python>>> a=1>>> def testfun():... global a... a=2... print a...>>> testfun<function testfun at 0x8176264>>>> testfun()2>>> a2>>>§1.10.8 (nested) Python>>> def outfun(a,b):... def innerfun(x,y):... return x+y... return innerfun(a,b)...>>> outfun(1,2)3 C C static Pascal§1.10.9 function python>>> def change(x,y):... x=2... y[0]="hello"...>>> x=1>>> y=[1,2]annCharles@tom.com 38 , 152 Python
  • 47. §1.11 (module) (package)>>> change(x,y)>>> x1>>> y[’hello’, 2] x y name space x y function local name space name function function x=2 name x bind name y[0]="hello" y bind y name space§1.11 (module) (package)§1.11.1 module module class (current direc-tory) testmodule.py"""this only is a very simple test module"""age=0 # a sample attributedef sayHello(): # a sample function in a moduleprint "Hello"if __name__ == "__main__"sayHello() module function doc string doc string doc string import module>>> import testmodule>>> print testmodule.__doc__ this only is a very simple test module>>>annCharles@tom.com 39 , 152 Python
  • 48. Python testmodule attribute>>> testmodule.age0>>> testmodule.age=1>>> testmodule.age1>>> testmodule.sayHello<function sayHello at 0x8174a34>>>> testmodule.sayHello()Hello>>> sayHello=testmodule.sayHello>>> sayHello()Hello>>> sayHello<function sayHello at 0x8174a34>>>>>>> othermodule=testmodule>>> othermodule.age=100>>> testmodule.age100 modname.attribute module attribute module class module attribute name space module name space module attribute module attribute module name space name sayHello=testmodule.sayHello() global name space name map( ) testmodule name space name object sayHello function object sayHello name space module object testmodule name global name space name testmodule object module object othermodule = testmodule module functions modulename.funcname import module python>>> from testmodule import age, sayHello>>> age0>>> sayHelloannCharles@tom.com 40 , 152 Python
  • 49. §1.11 (module) (package)<function sayHello at 0x81631a4>>>> sayHello()Hello>>> testmoduleTraceback (most recent call last): File "<stdin>", line 1, in ?NameError: name ’testmodule’ is not defined>>>import testmoduleage=testmodule.agesayHello=testmodule.sayHello from testmodule import name space testmodule name import testmodule name space testmodule name from testmodule import * testmodule name space name name space name name import testmodule testmodule.py reload(testmodule) testmodule§1.11.2 module python module import testmodule • testmodule.py • (environment variables) PYTHONPATH PATH • PYTHONPATH unix .:/usr/local/lib/python python sys.path module sys.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’]annCharles@tom.com 41 , 152 Python
  • 50. Python module module module module module§1.11.3 package( ) package module package • testpackage • testpackage __init__.py • testpackage testmodule py testmodule.py python>>> import testpackage.testmodule>>> testpackage.testmodule.sayHello()Hello package module name space package package modules§1.12 name space( ) name space name space python name space? name space (name) (object) (map) name object name object (bind) name object python object function module class package objects objects ? name! object name object object name object Charles Charles Charles Charles Python name space : build-in name space ( )global name space ( ) local name space( ) name space name name name spaceannCharles@tom.com 42 , 152 Python
  • 51. §1.12 name space( ) local name space name bind globalname space name object name space object.name object namespace name object name space “ ” object name space name name space name name “ ” object namespace “ ” name “ ” object name space “ ” name “ ” name space name space python file unix object module class function instance namespace name space name space module name space module import module python module module name space global name space name space module attribute __name__ module module __name__ __main__>>> print __name____main__ module __name__ attribute module moduleif __name__ == "__main__" sayHello() # modoule moduleimport name space name __name__ module import __name__ “__main__” python testmodule.py module import module name space global name space , python global name space __name__ “__main__” function function local name space function function exception local name space>>> def testfun():... print locals()annCharles@tom.com 43 , 152 Python
  • 52. Python... print globals()...>>>>>> testfun(){}{’__builtins__’: <module ’__builtin__’ (built-in)>, ’__name__’: ’__main__’, ’testfun’: <function testfun at 0x8174dd4>, ’__doc__’: None}>>> locals() globals() global name space local name space name space dictionary dictionary (key name) pair key name value name object scope( )? scope python (textually) “ ” name : • “ ” unqualified reference name name • unqualified reference . name a unqualified name a.b LGB scope : scope local name space scope module global name space scope buildin name space scope unqualifiedname L local G gloabl B buildin global unqualified name scope global name space function alias alias=module_name.funcname function>>> def sayHello():... print "Hello"...>>> saidHello=sayHello>>> saidHello<function sayHello at 0x8174bb4>>>> sayHello<function sayHello at 0x8174bb4>>>> sayHello()HelloannCharles@tom.com 44 , 152 Python
  • 53. §1.12 name space( )>>> saidHello()Hello sayHello saidHello object a=[1,2] name space name [1,2] object (bind) namespace name object java (reference) C pointer( ) del name space name>>> a=1>>> a1>>> del a>>> aTraceback (most recent call last): File "<stdin>", line 1, in ?NameError: name ’a’ is not defined name space name object (bind) name bind object java C C++ python name object object referece counter name object bind bind reference count 1 bind 1 reference counter 0 python tuple dictionary list string int long float module function class methord module class Basic Basicprint "1" + "2"12print 1 + "2"3 "1"+"2" "3" "12" name space namespace nameannCharles@tom.com 45 , 152 Python
  • 54. Python (variable) (name) module class alias ( )§1.13 Python (OO) Python C GTK C Unix “ ” open write read close ioctrl ( ) (encapsulation) (Inheritance) (Polymorphism) (abstraction) (interface) (implemetation)>>> class SimplestClass:... pass... class§1.13.1>>> class SampleClass:... def __init__(self):... print "OK, I was born."...>>> a=SampleClass()OK, I was born.>>> AClass = SampleClass>>> b=AClass()OK, I was born.>>> Python C++ object __init__annCharles@tom.com 46 , 152 Python
  • 55. §1.13 class (function) C++ template class template AClass = SampleClass function alias class alias class name space name space (virtual function) instance( ) obj=ClassName() obj name space§1.13.2 (method) class methord __init__ methord self C++ Java this methord self methord self : class methord obj classA instance sayHello(self) class A methord obj.sayHello() A.sayHello(obj) name space class name space instance name space class methord self methord local name space class instance obj=A_Class() instance instance namespace name space A_Class name space “ ” class instance name space class name space>>> class A:... def sayHello(self):... print "hello"...>>> obj=A()>>> obj.sayHello()hello>>> A.sayHello(obj)hello self instanceannCharles@tom.com 47 , 152 Python
  • 56. Python§1.13.3 (property) class name space class obj a obj.a =1 class methord self.a=1 obj.a=1 instance namespace class instance del instance>>> class A:... name="abc"...>>> obj1=A()>>> obj2=A()>>> obj1.name="xyz" # obj1 name>>> obj2.name # obj2’abc’>>> obj1.name # name space’xyz’ # .>>> class B:... def __init__(self):... self.a=1...>>> obj1=B()>>> obj2=B()>>> obj1.a #obj1 obj21 # a>>> obj2.a1>>> del obj2.a # obj2 a>>> obj2.a # , obj2.aTraceback (most recent call last): File "<stdin>", line 1, in ?AttributeError: B instance has no attribute ’a’>>> obj2.b=1 # obj2.b>>> obj2.b #obj2 b, a1 #obj1 a, b #class B instanceannCharles@tom.com 48 , 152 Python
  • 57. §1.13§1.13.4 (inherit) class <name>(superclass1,superclass2,...): name space superclass name space name name space namespace class name space superclass.methord(self,...) name space§1.13.5 (overload) C++ class name space instance name space class name name space bind superclass.methord(childInstance) name space§1.13.6 class attribute C++ Java class instance python name space instance name space class object name space instance name space __class__ name instance class __class__ python obj.__class__ obj class>>> class A:... count = 0... def __init__(self):... self.__class__.count= self.__class__.count + 1... # self.count>>> A.count # A instance0>>> a=A() # A instance>>> a.count # a.count A.count name space1>>> a.count = 2 # a.count>>> a.count2annCharles@tom.com 49 , 152 Python
  • 58. Python>>> A.count # A.count1 # A instance>>> a.__class__ # a name space __class__ name<class __main__.A at 0x81566d4>>>> a.__class__ is A # name A class bind .1 # , ,>>> b=A() # instance>>> A.count # __init__ self.__class__ 12 # self.__class__ A . # A instance .§1.13.7 Abstrace Class Java interface C++ abstract class pythonclass AbstractClass: def AbstrctMethord(self): raise NotImplementedError exception abstract class§1.13.8 Python OO ( ) OO Python java C++ SmallTalk Python namespace Pyton ( )§1.13.9 Python class methord Python class methord __init__ • __init__ obj=A_Class(arg,...) self A_Class • __del__(self) name object bindannCharles@tom.com 50 , 152 Python
  • 59. §1.13 • __repr__(self) repr() eval() • __str__(self) __repr__ __str__ >>> class A: ... def __repr__(self): ... return "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) python C++ • __cmp__(self,other) 0 1 −1 >>> 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"annCharles@tom.com 51 , 152 Python
  • 60. Python ... ok >>> __cmp__ ? python • __nozero__(self) None "" () 0 1 >>> 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 >>> • __len__(self) len object len(obj) >>> class EmptyClass: ... pass ... >>> obj=EmptyClass()annCharles@tom.com 52 , 152 Python
  • 61. §1.13 >>> len(obj) Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: EmptyClass instance has no attribute ’__len__’ >>> class Dog : ... def __len__(self): ... return 1000 ... >>> dog = Dog() >>> len(dog) 1000 __len__ __len__ len(dog) ? EmailBody class len(a_email_body) • __getitem__(self,key) self[key] 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’ __getitem__ sequence python object __getitem__ protocol ( ) java interface forannCharles@tom.com 53 , 152 Python
  • 62. Python >>> class A: ... def __getitem__(self,key): ... print "debug: key is %s"%key ... if key >=0 and key <=5: return key * key ... 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 return None for 0 key a while __tmp__ = 0 while(1): try : k = a[__tmp__] ... # for __tmp__ = __tmp__ +1 except IndexError: break for k in a for while forannCharles@tom.com 54 , 152 Python
  • 63. §1.13 • __setitem__(self,key,value) obj[key]=value >>> class A: ... def __setitem__(self,key,value): ... 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] >>> 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__ __getslice__(self,i,j) __setslice__(self,i,j,value) __delsclice__(self,i,j) 0 >>> 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:2annCharles@tom.com 55 , 152 Python
  • 64. Python None >>> print a[:] you want to get the slice 0:2147483647 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 in >>> 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,...) object >>> class A: ... def __call__(self,*arg):# , ... for k in arg: ... print k ... >>> a=A() >>> a("hello","World") hello World >>> •annCharles@tom.com 56 , 152 Python
  • 65. §1.14 (exception) __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 python class list dictionary list python module lib class lunix /usr/lib/python2/ UserList.py UserDict.py§1.14 (exception)§1.14.1 Cint fun1(){ ... if ( open(...) == -1 ){ return -1; } ...}int fun2()annCharles@tom.com 57 , 152 Python
  • 66. Python{ ... if (fun1()==-1){ return -1; } ...}int main(){ ... if(fun2()==-1){ return -1; }} C • • “ ” : unsigned int r; r=read(fd,buffer,len_of_buffer); for(i=0;i<r;i++){ // do something } read −1 for r “ ” • read −1 errnoannCharles@tom.com 58 , 152 Python
  • 67. §1.14 (exception) exception : • return • return return • ( ) • :def fun1() ... open file ...def fun2() ... fun1() ...def main() try : fun2() except exp : print "error message" return.§1.14.2 exception( )try : ... # statements 1except ExceptionType : ... # statements 2 : • statement 1 exception tryannCharles@tom.com 59 , 152 Python
  • 68. Python • exception exception except ExceptionType exception ExceptioinType • statement 2 • exception try exception • try 1/0 0 exception return C exception exception lib module exception try excepttry : ... # statements 1except (ExceptionType1,ExceptionType2) : ... # statements 2except (ExceptionType3,ExceptionType4) : ... # statements 3except: ... # statements 4 except exception exception try else exception else :try: f = open("/home/chunywang/tmp/test.py","r")except IOError: print "can not open file"else: for i in f.readlines(): print itry: f = open("/home/chunywang/tmp/test.py","r")annCharles@tom.com 60 , 152 Python
  • 69. §1.14 (exception) for i in f.readlines(): print iexcept IOError: print "can not open file" try IOError open readlines() exception try exception exception except exceptiontry: try: f = open("/home/chunywang/tmp/test.py","r") except IOError: print "can not open file" else: for i in f.readlines(): print iexcept IOError: print "read faid" : try: f = open("/home/chunywang/tmp/test.py","r") except IOError: print "can not open file" else: try: for i in f.readlines(): print i except IOError: print "read faid"try: f = open("/home/chunywang/tmp/test.py","r")except IOError: print "can not open file" return Nonefor i in f.readlines(): print iannCharles@tom.com 61 , 152 Python
  • 70. Python return readlines returntry: f = open (" ")except IOError:else :# elseisOpen=falsetry: f = open (" ") isOpen=trueexcept IOError: isOpen=falseif isOpen :else:# elsetry: ... # statements 1finally: ... # statements 2 except else exception return finally statements 2annCharles@tom.com 62 , 152 Python
  • 71. §1.14 (exception)>>> def fun():... try:... print "ok"... return 1... finally:... print "clean up"... return 1...>>> fun()okclean up1>>> return return finally return exception§1.14.3 exception raise exception exception object>>> from UserList import *>>> try:... raise UserList([1,2])... except UserList,arg:... for k in arg: print k...12 except exceptionType object exception object instance object class class object instance object class ... except exception object arg raise UserList([1,2]) ExceptionannCharles@tom.com 63 , 152 Python
  • 72. Python Exception : KeyError IndexError IOError python Exception exception raise raise classname,objectname objectname classname classname objectname classname except exception objectname except arg>>> try:... raise KeyError, "hello"... except KeyError, arg:... print arg...hello exception ) raise exception exception ( C ) trace ( ) (byte 0– 255) 256 “ ” exception tryannCharles@tom.com 64 , 152 Python
  • 73. §1.14 (exception) “ ” Exception C++ Exception C++ Python Java Python C++ Java Python ( glue language ) Perl VBScript Java Script Bash ( prototype development ) (Object Oriented) C++ Java (strong type) (dynamic type) Scheme LISP (regular expression) Perl Sed Awk Web Perl Doc String lambda LISP C++ Java VBannCharles@tom.com 65 , 152 Python
  • 74. Python Python§2.1 Emacs Python Emacs Emacs python mode Emacs python§2.1.1 python mode XEmacs 21.4.4 Python mode python mode : 1. python-mode.el Python 2.3 Misc http://www.python.org/emacs/python-mode/python-mode.el 2. python-mode.el : cp python-mode.el ~/emacs/ 3. ~/.emacs ;; Python ;; ;; emacs python-mode.el (add-to-list ’load-path "~/emacs") ;; *.py python modeannCharles@tom.com 66 , 152 Python
  • 75. §2.1 Emacs Python (setq auto-mode-alist (cons ’(".py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons ’("python" . python-mode) interpreter-mode-alist)) (autoload ’python-mode "python-mode" "Python editing mode." t) ;; (setq font-lock-maximum-decoration t) 4. Emacs M-x locate-library RET python-mode RET python-mode.el load-path§2.1.2 python mode Emacs python mode python • python TAB python mode backspace TAB TAB • • backspace • IM-Python • Python§2.1.3 1. C-c ! M-x py-shell pythonannCharles@tom.com 67 , 152 Python
  • 76. Python 2. C-c C-c M-x py-execute-buffer python python Python 3. C-c | M-x py-execute-region region region Emacs C-@ C-<SPC> region region region python Python 4. C-c RET M-x py-execute-import-or-reload module Python import reload C-c RET C-c C-c (a) (b) Python 5. C-c C-s M-x py-execute-string minibuffer python help(somefunc) type(somevar) dir(obj) 6. C-c C-# M-x comment-region region M-x uncomment-region region 7. C-c C-k M-x py-mark-block region C-x C-x region 8. C-M-a M-x py-beginning-of-def-or-classannCharles@tom.com 68 , 152 Python
  • 77. §2.2 C-M-e M-x py-end-of-def-or-class def class : C-u 1 C-M-a def class Emacs 9. C-M-h M-x py-mark-def-or-class def class region C-x C-x region Emacs 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 region 11. C-M-j M-x indent-new-comment-line 12. C-x $ M-x set-selective-display : C-u C-x $ C-x $ C-u 4 C-x $ 4 C-x $ python !§2.2 Emacshttp://www.python.org/cgi-bin/moinmoin/PythonEditors EmacsannCharles@tom.com 69 , 152 Python
  • 78. Python§2.3 pdb python GDB pdb pdb§2.3.1 DDD pydb python DDD GDB DDD pydb pdb pydb DDD 1. DDD Unix Linux DDD DDD 2. pydb http://ftp.debian.org/debian/pool/main/p/pydb/pydb_1.01.orig.tar.gz 3. pydb.py $PATH Shell : $cp pydb.py /usr/bin/pydb .py 4. pydbsupt.py pydbcmd.py import $cp pydbsupt.py pydbcmd.py /usr/local/lib/python/ 5. $ddd --pydb Edit/Preference.../Source “Refer to Program Source” “by Full Path Name” 6. File/OpenannCharles@tom.com 70 , 152 Python
  • 79. Python§3.1 import print obj.__doc__§3.1.1 3.1-1 :>>> 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 theannCharles@tom.com 71 , 152 Python
  • 80. Python help(obj) obj callable(obj) obj repr(obj) obj eval eval(str) str python dir(obj) obj name space name hasattr(obj name) obj name space name getattr(obj name) obj name space name setattr(obj name value) obj name space name value object delattr(obj name) obj name space name vars(obj) object name space dictionary locals() name space dictionary globals() name space dictionary type(obj) obj isinstance(obj cls) obj cls instance issubclass(subcls supcls) subcls supcls 3.1-1: Python attributes of its bases. Otherwise: its attributes, its class’s attributes, and recursively the attributes of its class’s base classes.>>> callable(dir) #1>>> a=1>>> callable(a) #0>>> a=dir # aliase>>> callable(a)1annCharles@tom.com 72 , 152 Python
  • 81. §3.1>>> 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"{’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)<type ’list’>§3.1.2 3.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 73 , 152 Python
  • 82. Python chr(i) ASCII ord(i) unicode ASCII oct(x) x hex(x) x str(obj) obj list(seq) sequence list tuple(seq) sequence tuple dict() dict(list) dictionary int (x) integer long(x) long integer float(x) complex(x) max(... min(...) 3.1-2:>>> 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.2Traceback (most recent call last): File "<stdin>", 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 74 , 152 Python
  • 83. §3.1>>> 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 import module exec code [ in globaldict[,localdict]]>>> exec "a=1" # namespace .>>> a1>>> mynamespace={} # dictionary, namespace>>> exec "a=1" in mynamespace # mynamespace .>>> print mynamespace.keys() #[’__builtins__’, ’a’] # name>>> type(mynamespace["__builtins__"])<type ’dict’>#>>> class A: # class... pass...>>> exec "a=1" in vars(A) #>>> A.a #1>>> exec "def abc(self): print ’ok’ " in vars(A)# methord>>> dir(A) # , abcannCharles@tom.com 75 , 152 Python
  • 84. Python[’__builtins__’, ’__doc__’, ’__module__’, ’a’, ’abc’]>>> x=A()>>> x.abc() #ok>>> C++ Java Python Python C++ C++ C++ ? C++ Python C++ Python C++ C++ python profilemodule python “ ” “ ” compile>>> c=compile("print ’hello’","abc","single")>>> exec chello>>> c=compile("raise 1 ","abc","single")>>> exec cTraceback (most recent call last): File "<stdin>", line 1, in ? File "abc", line 1, in ? # abcTypeError: exceptions must be strings, classes, or instances,not int compile Python “single” “exec” “eval”>>> code="print ’Hello World’"annCharles@tom.com 76 , 152 Python
  • 85. §3.1>>> c=compile(code,"abc","exec")>>> profile.run("for i in range(10000): exec c") 10002 function calls in 0.250 CPU secondsOrdered by: standard namencalls tottime percall cumtime percall filename:lineno(function) 1 0.090 0.090 0.250 0.250 <string>: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 secondsOrdered by: standard namencalls tottime percall cumtime percall filename:lineno(function)10001/1 0.720 0.000 0.720 0.720 <string>: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) 0.250 CPU seconds 0.720 CPU second 3 eval(str)>>> a=2>>> eval("a==1")0>>> eval("a=1")Traceback (most recent call last): File "<stdin>", line 1, in ? File "<string>", line 1 a=1 ^annCharles@tom.com 77 , 152 Python
  • 86. PythonSyntaxError: invalid syntax§3.2 sys import sys (command line arguments) sys.argv list sys.stdout sys.stdin sys.stderr sys.exit(exit_code) modules sys.modules dictionary module sys.modules["os"] module os sys.platform sys.path list module package os import os os.environ dictionary os.environ["HOME"] HOME os.chdir(dir) os.cwd() os.getegid() id os.getgid() id os.getuid() id os.geteuid() id os.setegid() id os.setgid() id os.setuid() id os.seteuid() id os.getgroups() os.getlogin() os.getenv os.putenv os.umask umask 3.2-3: 3.2-3 pythonannCharles@tom.com 78 , 152 Python
  • 87. §3.2 shell os.system() shell#!/usr/bin/pythonimport os,syscmd=sys.stdin.readline()while cmd: os.system(cmd) cmd=sys.stdin.readline() os.system(cmd) os shell>>> os.mkdir(’/tmp/xx’) #>>> 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’) #Traceback (most recent call last): File "<stdin>", line 1, in ?OSError: [Errno 2] No such file or directory: ’/tmp/xx’ chown chmod unlink symlink link Unix os POSIX Unix Python Unix POSIX Advanced Programming In Unix Environments UnixannCharles@tom.com 79 , 152 Python
  • 88. Python pipe dup open os.path os.path Windows(DOS) MAC Unix DOS C:tempa.txt Unix /tmp/a.txt :>>> os.getcwd()’/home/Charles’>>> os.path.split(os.getcwd())(’/home’, ’Charles’)# .>>> print os.path.join(os.getcwd(),os.pardir,’a’,"a.doc")/home/Charles/../backup/a.doc# split , .#os.pardir ..>>> print os.path.exists(os.getcwd())1# .>>> os.path.expanduser(’~/dir’)’/home/Charles/dir’# ~ .# Windows H:Charlesdir>>> os.path.expandvars(’$TMP’)’/tmp’# ,Windows c:temp>>> os.path.isfile(os.getcwd())0# 0,>>> os.path.isfile(os.path.expanduser("~/tmp/a.c"))1# /home/Charles/tmp/a.c>>> os.path.isdir(os.getcwd())1# 1,>>> os.path.islink(os.getcwd())0annCharles@tom.com 80 , 152 Python
  • 89. §3.2# Windows>>> os.path.ismount(os.getcwd())1# Windows>>> os.path.samefile(os.getcwd(),’/home/Charles’)1# .>>> 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 os.path.walk(p,func,arg) os.path.walk p p func func(arg,dirname,names) walk arg dirname names list dirname 4 a.c Unix Windows§3.2.1 file string integer floatf=open("filename","r") filename “r” “w” “rw” “rb” “wb”§3.2.2 open file >>> 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 81 , 152 Python
  • 90. Python’’ f.read(size) size size f.read(size)f.open("/tmp/x.txt","r")c=f.read(1)while c: print c c=f.read(1) f.readline() f.readlines() list list “n” f.write(str) f.tell() f.seek(off,where) where= 0 1 2 off sys sys.stdout sys.stderr sys.stdin>>> import sys>>> a=sys.stdin.readline()Hello #>>> sys.stdout.write(a)Hello #>>> writeline write writelines§3.2.3 Python f.close()§3.3 regular expression regular expression ( ) regexp Unix vi emacs sed awk perl python reannCharles@tom.com 82 , 152 Python
  • 91. §3.3 regular expression regexp module perl regexp regexp (set) regexp (match regexp Python match regexp match§3.3.1 regexp regexp>>> p=re.compile("abc")>>> if p.match("abc") : print "match"...match>>> re.compile("abc") pattern ( ) pattern match match object None metacharacter ( ) ^ $ * + ? { [ ] | ( )§3.3.2 [] • [abc] a b c a b c [abc] metacharacter [] metacharacter : >>> 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 matchannCharles@tom.com 83 , 152 Python
  • 92. Python [+] is match [?] is match [{] is match [] is not match [|] is match [(] is match [)] is match metacharacter [] metacharacter “^[]” ^ [] [] • [] [] “[” “]” ? >>> 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> [ ] • ^ [] [] [^abc] a b c ^ [] ^ ^ • - [a-zA-Z] [0-9] • [] d [0-9] D [^0-9] s [ tnrfv] S [^ tnrfv] w [a-zA-Z0-9_] W [^a-zA-Z0-9_] t tab x20 ascii 0x20 [] “.” [] n [^n]annCharles@tom.com 84 , 152 Python
  • 93. §3.3 regular expression§3.3.3 regexp • {m,n} m ( m ) n ( n ) ab{1,3}c abc abbc abbbc ac abbbbc m n m 0 n • * {,} (0 ) 1 • + {1,} 1 • ? {0,1} 0 1 [ab]* ababab a ababab a ababab python>>> re.compile("a*").match(’aaaa’).end()4>>> re.compile("a*?").match(’aaaa’).end()0match object end * + ? {m,n} ? *? +? ?? {m,n}?§3.3.4 regexp regexp regexp re.compile("") r raw python regexp r>>> a=r"a">>> print aa>>> a=r""a">>> print a"a>>>§3.3.5 re regexpannCharles@tom.com 85 , 152 Python
  • 94. Python • re.compile RegexObject regexp • pattern match search MatchObject • match objectRegxObject : • RE_obj.match(str,[pos[,endpos]]) str RE_obj MatchObject None str >>> re.compile("a").match("abab") <_sre.SRE_Match object at 0x81d43c8> >>> print re.compile("a").match("bbab") None • RE_obj.search(str,[pos[,endpos]]) str 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> match() • RE_obj.findall(str) str RE_obj tupleMatchObject • m.start() RE_obj.match() MatchObject start() 0 • m.end() ( ) >>> 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 86 , 152 Python
  • 95. §3.3 regular expression • m.span() tuple (m.start(),m.end()) • m.pos() m.endpos() m.re() m.string() 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 MatchObject >>> for m in re.compile("[ab]").finditer("tatbxaxb"): ... print m.span() ... (1, 2) (3, 4) (5, 6) (7, 8)§3.3.6 regexp regexp • | regexp A B regexp A|B A B | Good|Bad “Good” “Bad” “Goodad” “GooBad” • ^ “^abc” “abc” “xabc” search ^ ^ metacharacter ^ • $ ^ $ • A (MULTILINE) A ^ A ^ • Z (MULTILINE) Z $ Z ^ • b locale binfob “info” “information”annCharles@tom.com 87 , 152 Python
  • 96. Python >>> print re.compile(r"binfob").match("info ") # raw <_sre.SRE_Match object at 0x817aa98> #b >>> print re.compile("binfob").match("info ") # raw None #b >>> print re.compile("binfob").match("binfob ") <_sre.SRE_Match object at 0x8174948> r raw b 0x8 raw b • B metacharacter : ^abc “abc” 3 1§3.3.7 (Group) regexp email email header( ) email body ( ) email header emailname: CharlesAddress: BUPTtelephone: 62281234email: annCharles@tom.comname: AnnAddress: BUPTtelephone: 62284321email: CharlesWang@peoplemail.com.cn Charles Ann BUPT ? Group !>>> x="""... name: Charles... Address: BUPT... telephone: 62281234... email: annCharles@tom.com... 1 lex “ˆbc” a “abc”annCharles@tom.com 88 , 152 Python
  • 97. §3.3 regular expression... 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.comhere is your friends list Ann, BUPT, 62284321, CharlesWang@peoplemail.com.cn p.compile() (.*) group MatchObject groups() group Charles MatchObject start() end() span() group() group 0 1 regexp group m.start(1) name m.start(2) Address group ( :>>> re.compile("(a(b)c)d").match("abcd").groups()(’abc’, ’b’)>>> ( abc b p.finditer(x) MatchObject print m.groups() m.groups() tuple string group : (bw+)s+1 m.group(1) name group group m.group(’name’) name :>>> p=re.compile(r"^name:(?P<name>.*)n^Address:(?P<address>.*)n" r"^telephone:(?P<telephone>.*)n^email:(?P<email>.*)n",re.M)>>> for m in p.finditer(x):annCharles@tom.com 89 , 152 Python
  • 98. Python... 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’ (?P<xxx>.*) (.*) m.group(’xxx’) group group regexp python Perl 5 Python (?=<xxx>) regexp : (bw+)s+1 (?P<n>bw+)s+(?=<n>) group group Non-capture group group MatchObject group (?:...) Non-capture group :§3.3.8 Compile Flag re.compile RegxObject flag RegxObjectannCharles@tom.com 90 , 152 Python
  • 99. §3.4 struct DOTALL S . n IGNORECASE I LOCALES L w W b B locale MULTILINE M ^ $ VERBOSE X verbose§3.4 struct C structstruct{...} header;write(fd,(void*) &header,sizeof(struct));read(fd,(void*) &header,sizeof(struct)); Python struct pack unpack cacsize C :$cat a.c#include <stdio.h>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.dat0000000: 0200 0100 5741 5645 ....WAVEannCharles@tom.com 91 , 152 Python
  • 100. Python C xxd 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])>>> ver2>>> subver1>>> tag’WAVE’ unpack struct 3.4-4 3.4-4 C Python x char ( ) c char 1 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 3.4-4: structannCharles@tom.com 92 , 152 Python
  • 101. §3.5 Cmd @ native native = native standard < little-endian standard > big-endian standard ! network (= big-endian) standard 3.4-5: • q Q 64 • >>> struct.unpack(’2h4s’,data[start:stop]) (2, 1, ’WAVE’) • x >>> struct.unpack(’xxh4s’,data[start:stop]) (1, ’WAVE’) • s 4s 4 p “Pascal String” 256 • P 64 long integer 32 integer struct Intel CPU little-endian SPARC CPU big-endian C 3.4-5: :>>> data’x02x00x01x00WAVE’>>> struct.unpack(’!hh4s’,data)(512, 256, ’WAVE’)>>> struct.unpack(’<hh4s’,data)(2, 1, ’WAVE’) pack unpack§3.5 Cmd /usr/lib/python2.2 cmd.pyannCharles@tom.com 93 , 152 Python
  • 102. Python GDB Python Bash Octave Gnuplot Cmd readline 3.5-6 readline gnuplot C-a C-e C-u C-w C-y C-f C-b M-f M-b 3.5-6: Cmd cmd.py 269 47 cmd.py§3.5.1 demo cmd.py# cmd.py class Cmdfrom cmd import *# Cmdclass CmdInterface(Cmd): # # argc def do_say_hello(self,argc): print "hello! " + argcif __name__=="__main__" : # welcome welcome ="welcome a simple command interface demo demo" # CmdInterface().cmdloop(welcome) :annCharles@tom.com 94 , 152 Python
  • 103. §3.5 Cmd%python demo_cmd.pywelcome a simple command interface demo demo(Cmd) helpUndocumented commands:======================help say_hello(Cmd) say_hellohello!(Cmd) say_hello Charleshello! Charles do_foo foo do_foo argc foo xxx xxx cmd_loop cmd_loop readline Cmd help§3.5.2 default(self,line) line Cmdprint ’*** Unknown syntax:’, line§3.5.3 EOF EOF(Control-D)% echo "say_hello Charles" | python demo_cmd.py EOF def do_EOF(self,arc): return 1 do_EOF Control-D do_xxx cmd_loop “ exit”annCharles@tom.com 95 , 152 Python
  • 104. Python def do_exit(self,arc): return 1§3.5.4 : def emptyline(self): pass emptyline§3.5.5 Bash tab : def complete_say_hello(self,text,line,begingidx,endidx): x=["Charles","Smith","Tom"] return [ k for k in x if k.find(text)==0] “say hello” tabCharles Smith Tom “C” tab “Charles” complete_say_hello say_hello text line beginidx text line endidx text line tab init x=CmdInterface("?") “?”§3.5.6 init sys.stdin sys.stdoutannCharles@tom.com 96 , 152 Python
  • 105. §3.5 Cmd§3.5.7 Cmd “Cmd” prompt : x=CmdInterface() x.prompt="?" x.cmdloop(welcome)§3.5.8 help “Undocumented commands:” Cmd • Undocumented commands: • Documented commands: • Miscellaneous help topics: topic say_hello Undocumented commands. : def help_say_hello(self): print """ say_hello [<person>] say hello to somebody """ say_hello Documented commands. “ help say hello” help_say_hello : def help_test(self): print """ this is only a test topic """ “test” Miscellaneous help topics “help test” help_test “?test” “?say hello”annCharles@tom.com 97 , 152 Python
  • 106. Python§3.5.9 Shell : def do_shell(self,argc): import os os.system(arg) “shell ls” “!ls” shell§3.5.10 getattr getattr Cmd Cmddef onecmd(self, line): # line # line cmd, arg, line = self.parseline(line) try: # do_cmd func = getattr(self, ’do_’ + cmd) except AttributeError: return self.default(line) # func return func(arg) getattr func callable(func) do_cmd help_cmd getattr • Undocumented commands: do_cmd help_cmd • Documented commands: do_cmd help_cmdannCharles@tom.com 98 , 152 Python
  • 107. §3.6 • Miscellaneous help topics: do_cmd help_cmd§3.6 Unix Unix :ls -l -agrep -i a somefile getopt module getopt.py /usr/lib/python2.2/§3.6.1 demo_getopt.py# getoptfrom getopt import *import sysopts,args = getopts(sys.argv[1:],"a","--all")print optsprint args :%python demo_getopt.py -a f[(’-a’, ’’)][’f’]%python demo_getopt.py[][]%python demo_getopt.py --all[(’--all’, ’’)][]%python demo_getopt.py -xTraceback (most recent call last): File "demo_getopt.py", line 4, in ?annCharles@tom.com 99 , 152 Python
  • 108. Python 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 getopt 3 • sys.argv[1:] • "a" “-” ls -a a • ["all"] list “-” “–” getopt tuple opts,args args sys.argv[1:] opts list list tuple pair,(opt,val) opt val opts GetoptError GetoptError msg opt§3.6.2 getoptgetopt(sys.argv[1:],"a:","all") GetoptError :annCharles@tom.com 100 , 152 Python
  • 109. §3.6%python demo_getopt.py -aTraceback (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’)][] : getopt(sys.argv[1:],"a:","all=") :%python demo_getopt.py -a b --all xx file1 file2[(’-a’, ’b’), (’--all’, ’xx’)][’file1’, ’file2’]§3.6.3 optparser optparser Python 2.3 optparser getopt#!/usr/bin/env python# simplyOptparser1.pyfrom optparse import OptionParserparser = 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 101 , 152 Python
  • 110. Python(options, args) = parser.parse_args()D = vars(options)for i in D: print i,"=",D[i] GNU option%./simplyOptparser1.py -f output --quietverbose = Falsefilename = output%./simplyOptparser1.py -qf outputverbose = Falsefilename = output%./simplyOptparser1.py -q --file=outputverbose = Falsefilename = output%./simplyOptparser1.py --quiet --file=outputverbose = Falsefilename = output%./simplyOptparser1.py --helpusage: 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 --versionsimplyOptparser1.py 0.1%optparser optparser Unix GNU : • argument ( )annCharles@tom.com 102 , 152 Python
  • 111. §3.6 %ls -l /usr -l usr sys.argv list sys.argv [’ls’,’-l’,’/usr’] sys.argv[1:] sys.argv[0] • option ( ) argument Unix GNU : -q -f --file --quiet -qf optionparser • -pf -p -f -pf • -file -file -f -i -l -e • +f +rgb • /l /rgb Windows VMS Unix ls /l— /l • option augument( ) -f outputfile outputfile -foutputfile -f outputfile optional option argument ( ) -a optional option argument: ls -a xxx -b -a xxx |ls -a -b| -a ls -ab optionparser optional option argumentannCharles@tom.com 103 , 152 Python
  • 112. Python • positional argument ( ) positional argument ls -l /usr /lib [’/usr’, ’/lib’] positional argument • required option ( ) option option : prog -v --report /tmp/report.txt foo bar : progargument : -v --report /tmp/report.txt foo baroption : -v --reportoption argument : /tmp/report.txtpositional argument : foo bar • option Unix GNU find, tar, dd • required option positional argument • option • option shell ls -l --long : cpcp SOURCE DESTcp SOURCE ... DESTDIR cp cpannCharles@tom.com 104 , 152 Python
  • 113. §3.6 positional argument cat, sort, cut, grep, sed, awk, head, tail, ed, uniq, fold, wc, fmt,split,od, xxd, sum, positional argument diff, join, tr, : diff ? join tr positional argument cut%cutcut: you must specify a list of bytes, characters, or fieldsTry ‘cut --help’ for more information. cut byte character field cut -f 1 cut -b1 cut -c1 17 command line, GUI option option Preferences 1000 option option 1. import optparse parser = optparse.OptionParser() OptionParser 2. parser.add_option("-f","--file",...) optionannCharles@tom.com 105 , 152 Python
  • 114. Python 3. (options, args) = parser.parse_args() options option args positional argument add_option option option : 1. option : parser.add_option("-f", "--file", action="store", type="string", dest="filename") action option : -f --file filename : args = ["-f", "foo.txt"] parser.add_option("-f", "--file", action="store", type="string", dest="filename") (options, args) = parser.parse_args(args) print options.filename foo.txt type int float string dest option option options.filename 2. option action = "store"annCharles@tom.com 106 , 152 Python
  • 115. §3.6 action = "store_false" action = "store_true" : parser.add_option("-v", action="store_true", dest="verbose") parser.add_option("-q", action="store_false", dest="verbose") -v -q verbose True False 3. option option None parser.add_option("-v", action="store_true", dest="verbose") parser.add_option("-q", action="store_false", dest="verbose", default=True) parser.add_option("-v", action="store_true", dest="verbose", default=True) parser.add_option("-q", action="store_false", dest="verbose") parser.add_option("-v", action="store_true", dest="verbose", default=False) parser.add_option("-q", action="store_false", dest="verbose", default=True) verbose True 4. : % ./optparser.help.py --help usage: optparser.help.py [options] arg1 arg2 options:annCharles@tom.com 107 , 152 Python
  • 116. Python -h, --help show this help message and exit -v, --verbose make lots of noise [default] -q, --quiet be vewwy quiet (I’m hunting wabbits) -fFILE, --file=FILE write output to FILE -mMODE, --mode=MODE interaction mode: one of ’novice’, ’intermediate’[default], ’expert’ % : (a) usage %prog sys.argv[0] usage ’usage : %prog [options]’ (b) option help help (c) meta-variable -mMODE -fFILE metavar metavar option 5. option option : : $./opt.group1.py --help usage: opt.group1.py [options] arg1 arg2 options: -h, --help show this help message and exit -v, --verbose make lots of noise [default] -q, --quiet be vewwy quiet (I’m hunting wabbits) -fFILE, --file=FILE write output to FILE -mMODE, --mode=MODE interaction mode: one of ’novice’, ’intermediate’[default], ’expert’ Dangerous Options:annCharles@tom.com 108 , 152 Python
  • 117. §3.7 Caution: use these options at your own risk. It is believed that some of them bite. -g Group option. $ : (a) OptionGroup parser group group option group (b) parser group option (c) add_option_group group parser 6. usage parser version -v --version option parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") %prog sys.argv[0]§3.7 time C C : • epoch ( ) epoch epoch epoch 0 epoch epoch 0 UNIX epoch 1970 1 1 0 0 0 epoch C UNIX 2038 • 2000 Python C 2000 epoch python-libannCharles@tom.com 109 , 152 Python
  • 118. Python • UTC (Coordiated Universal Time) GMT (Greenwich Mean Time) • DST( Daylight Saving Time) C gmtime() , localtime(), strptime() asctime(), mktime() ,strftime() tuple 9 9 ?? 0 tm_year 1993 1 tm_mon 1 – 12 2 tm_mday 1 – 31 3 tm_hour 0 – 23 4 tm_min 0 – 59 5 tm_sec 0 – 61 6 tm_wday 0 – 6, Monday is 0 7 tm_yday 1 – 366 8 tm_isdst 0, 1 or -1 3.7-7: 3-1 time +timezone seconds(local) seconds(UTC) -timezone ctime gmtime localtime mktime string strptime strftime struct time(local time) struct time(UTC) 3-1:annCharles@tom.com 110 , 152 Python
  • 119. Tkinter§4.1 Tkinter§4.1.1 Tkinter Tkinter python Tcl/Tk Tcl/Tk ( ) Unix Tcl/Tk Windows MacOS Tcl/Tk Tk C tkinter Tkinter.py tkinter Python Python 4-1 X windows Your App Here(Python) Tkinter(Python Module) tkinter(C) Tk Widgets(C and Tcl) Tk(C) Xlib (C) 4-1: TkinterYour App Here (Python) Python Tkinter.py gvTkinter (Python Module) Tkinter.py Python Tktkinter (C) Tkinter.py Tk TkannCharles@tom.com 111 , 152 Python
  • 120. TkinterTk Widgets (C and Tcl) Tk C TclTk (C) Tk CXlib (C) X X Server Python tkinter Tkinter.py Tkinter Python Tcl/Tk Python Python Tcl/Tk Tcl/Tk Tkinter from Tkinter import * import Tkinter Tkinter Tkinter.somefunc() Widget ? Widget Button( ) Canvas( ) Menu( ) Label( ) Message( ) Listbox( ) Entry ( ) Frame( ) Radiobutton( ) CheckButton( ) Scrollbar( ) Text( ) Scale( ) TopLevel( ) option ? Widget options fg( ) bg( ) font( ) command( ) text( )§4.2 Hello Tkinter§4.2.1 “Hello World”# File: hello1.py# Tkinterfrom Tkinter import *# root Widget# Tkinter# root widgetannCharles@tom.com 112 , 152 Python
  • 121. §4.2 Hello Tkinter# Windows# Manage# Widget root widget# Tkinterroot = Tk()# Label w# root w master( )# w root slave ( )# Windows Windows# parent window child window# text w option ( ) w#w = Label(root, text="Hello, world!")# w# pack Label# Labelw.pack()## quit()# mainloop() widget# Windows Managerroot.mainloop() %python hello1.py 4-2 4-2: hello1.py WM(Windows Manager) X Windows WM Windows X WM WMannCharles@tom.com 113 , 152 Python
  • 122. Tkinter X Client X Server X client WM Windows WM Win XP Win 2000 Windows WM Windows MacOS X WM§4.2.2# File: hello2.pyfrom Tkinter import *class App: def __init__(self, master): # Frame widget frame = Frame(master) frame.pack() # 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() §4.2.2 ”Hello” “hi there, everyone!” w widget w.pack(side=LEFT) wannCharles@tom.com 114 , 152 Python
  • 123. §4.3 Widget§4.3 Widget Tk widget option option widget option Tkinter option. widget option: • widget widget options widgetclass (master , option=<value> ...) : w = label(root,text="hello",fg="red") widget w master widget root option widget option widget option option widget master widget master widget Tkinter master widget master widget • w.cget(option) widget option w widget widget class __getitem__ w.cget w[option] option : w = Label(text="abc") print w.cget("text") print w["text"] # abc w[’text’] • w.configure w.config option w.config w.configure widget w.config(option=<value>, ... ) : w.config(text="xxx")annCharles@tom.com 115 , 152 Python
  • 124. Tkinter widget class __setitem__ w.config w["text"] = ’xxx’ option config options 1 • config widget option w.keys() w.keys() : for k in w.keys(): print "%s = %s"%(k,w[k]) widget option widget option w.config() w.keys() w.config(optionname=optionvalue,...) w[’optionname’]=optionvalue w.cget(’optionname’) w[’optionname’]§4.4 Geometry Manager( ) Geometry Manager? GUI Widget Widget Widget Master Master Widget Tk Geemetry Manager Delphi VB VB WYSIWYG Whatyou see is what you get ( ) Geometry Manager WYTIWYG What you think is what you get ( ) TeX(LaTeX) Word VB Widget “ / ” Geometry Manager Tk Geometry Manager : 1annCharles@tom.com 116 , 152 Python
  • 125. §4.4 Geometry Manager( ) • Pack • Grid • Place§4.4.1 Pack cavity : master widget slave widget master widget slave widget parcel : cavity slave widget slave widget cavity parcel slave widget parcel cavity parcel cavity slave widget Pack w.pack(options) w slave widget options :Pack optionside w TOP ( ) BOTTOM( ) LEFT( ) RIGHT( )padx pady parcel wipadx ipady w w wfill None, x, y , both parcel fill slave widget • None: slave widget • X: slave widget • Y: slave widget • BOTH: slave widget fill slave widget parcel slave widget parcelanchor parcel slave widget CENTERannCharles@tom.com 117 , 152 Python
  • 126. Tkinter W E N S NW NE SW SE CENTER fill X anchor W E slave widget fill Y anchor N S fill BOTH anchor option gridexpand 0 1 1 slave widget master slave widget parcel 0 expand master slave widget parcel slave widget master parcel option side padx , pady , ipadx , ipady , expand, fill pack() option widget optionPack master widget packing list slave widget slave widget master widget Packing list slave widget in , after , before option Pack packing list widget widget master widget cavity ( ) Pack slave widget 1. cavity parcel ( ) side option side = TOP side = BOTTOM parcel cavity slave widget pady ipady options side = LEFT side = RIGHT parcel cavity slave widget padx ipadx options parcel expand option slave widget master widget expand option parcel expand option 0annCharles@tom.com 118 , 152 Python
  • 127. §4.4 Geometry Manager( ) expand option 1 parcel slave widget side option left right slave widget side option top bottom grid 2. pack slave widget widget ipadx widget ipady ? ipadx ipady fill option X BOTH slave widget parcel padx fill option Y BOTH slave widget parcel pady 3. pack slave widget parcel slave widget parcel anchor option slave widget parcel slave widget padx option pady option 0 parcel slave widget padx pady slave widget pack parcel cavity slave widget cavity slave widget slavewidget cavity cavity 0 slave widget master widget master widget Geometry Propragation ( ) Geometry propragation master widget slave widget widget widget ? master widget slave widget master widget widget slave widget widget widget slave widget slave widget widget slave widget TopLevel Widget Geometry Propagation w.pack_propagate(’true’) Pack frame widget widget widgetannCharles@tom.com 119 , 152 Python
  • 128. Tkinter§4.4.2 Grid Pack Grid Grid Pack Grid Pack Grid Pack w.grid(options) w slave wid-get Grid master widget Cell Pack parcel row column rowspan columnspan cell option optionsrowcolumnrowspancolumnspanipadx ipady Pack slave widgetpadx pady slave widget cellsticky N W S E Pack fill anchor Cell slave widget slave widget slave widget N Pack anchor= N N+S Pack fill = Y E+W Pack fill = X N+E fill=None anchor=NE N+W+S+E Pack fill=BOTH sticky Pack anchor=CENTER fill=NoneannCharles@tom.com 120 , 152 Python
  • 129. §4.4 Geometry Manager( )Grid : 1. slave widget 2. master widget master widget 3. slave widget sticky options slave widget ( ) cell ( ) rowspan=1( colspan=1) cell ( ) ( ) ( ) ( ) slave widget cell ( ) cell cell ( ) cell group cell group ( ) cell ( ) cell group slave widget ( ) ( ) Cell ( ) ( ) () weight( ) cell group ( ) ( ) weight weight weight 0 cell group cell weight 0 cell ( ) ( ) ( ) cell cell group weight grid rowconfgure m.grid_rowconfigure(0,weigtht=2) 0 weight 2 weight grid columnconfgure m.grid_columnfigure(0,weigtht=2) 0 weight 2 m slave widget master widget master widget ( ) ( ) ( ) weight weight weight weight 0 ( ) weight 0 ( ) ( ) weight Pack expand option Grid option Pack option Pack Grid Grid Pack frame optionannCharles@tom.com 121 , 152 Python
  • 130. TkinterPlace Place slave widget VB top left bottom right§4.5 Widget widget option option widget§4.5.1 widget background option foreground option widget widget bg fg background foreground bg fg background foreground RGB red, green Tkinter RGB red , yellow , blue , green lightblue Moccasin, PeachPuff, etc. X windows X windows rgb.txt /usr/X11R6/lib/X11/ RGB Windows Windows ( ) SystemActiveBorder, SystemActiveCaption, SystemAppWorkspace, SystemBack-ground, SystemButtonFace, SystemButtonHighlight, SystemButtonShadow, SystemBut-tonText, SystemCaptionText, SystemDisabledText, SystemHighlight, SystemHighlightText,SystemInactiveBorder, SystemInactiveCaption, SystemInactiveCaptionText, SystemMenu,SystemMenuText, SystemScrollbar, SystemWindow, SystemWindowFrame, SystemWin-dowText. Macintosh : SystemButtonFace, SystemButtonFrame, SystemButtonText, SystemHighlight, Sys-temHighlightText, SystemMenu, SystemMenuActive, SystemMenuActiveText, System-MenuDisabled, SystemMenuText, SystemWindowBody.annCharles@tom.com 122 , 152 Python
  • 131. §4.5 Widget ”light blue” ”LightBlue”RGB RGB #RGB,#RRGGBB, #RRRRGGGGBBBB : w["fg"]="#f00" w["fg"]="#ff0000" w["fg"]="#ffff00000000" RGB RGB tk_rgb = "#%02x%02x%02x" % (172, 182, 220) tk_rgb = "#%04x%04x%04x" % (172, 182, 220) w.wininfo_rgb() RGB rgb = widget.winfo_rgb("red") red, green, blue = rgb[0]/256, rgb[1]/256, rgb[2]/256 winfo_rgb 0 – 65535 0 – 256 256 8§4.5.2 Tkinter widget Tk widget Label Button font option Tkinter • (font descriptor ) • tkFont • • X ( X font descriptor) (font descriptor) Tk 8.0 Tkinter (font style)annCharles@tom.com 123 , 152 Python
  • 132. Tkinter ("Times", 10, "bold") ("Helvetica", 10, "bold italic") ("Symbol", 8) (font style) "Times 10 bold" "Helvetica 10 bold italic" "Symbol 8" Windows : Arial (corresponds to Helvetica), Courier New (Courier), Comic Sans MS, Fixedsys, MS Sans Serif, MS Serif, Symbol, System, Times New Roman (Times), and Verdana: : normal, bold, roman, italic, underline, overstrike. Tk 8.0 Courier, Helvetica, Times Tk 8.0 Tk Windows Tk 4.2 tkFont Font (font descriptor) tkFont Font tkFont Tkinter tkFont :annCharles@tom.com 124 , 152 Python
  • 133. §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 w.config(font=myfont) widget w myfont myfont.config(size=40) myfont widget font propagate widget myfont myfont widget tkFont.Font option 4.5-1: Option family string size integer point pixel weight constant NORMAL BOLD NORMAL. slant constant NORMAL ITALIC NORMAL. underline flag 1 0 overstrike flag 1 0 4.5-1: tkFont option Tk X Windows fixed, 6x10 Windows ansi, ansifixed, device, oemfixed, system, and systemfixed Macintosh application and systemX Font Descriptor X Font Descriptor -*-family-weight-slant-*--*-size-*-*-*-*-charset family weight Bold NormalannCharles@tom.com 125 , 152 Python
  • 134. Tkinter slant R Roman I O oblique size point 72 point = 1 inch charset ISO8859-1 -*-Times-Bold-R-*--*-120-*-*-*-*-ISO8859-1 12 point Times ISO Latin 1 X Server Times, Helvetica, Courier, 8 , 10 , 12, 14,18 , 24 . xlsfonts xfontsel Unix Windows Macintosh Windows Macintosh§4.5.3 Label Button "n" justify option LEFT RIGHT wraplength option§4.5.4 Widget Widget 3D Relief( ) Focus Highlight( ) relief option Widget SUNKEN RAISEDGROOVE RIDGE FLAT borderwidth bd option widget 2 1 Focus Highlight Region ( ) widget widget Focus Highlight Region widget highlightcolor option widget Focus Highlight Region highlightbackground option widget Focus High-light Region widget highlightthickness Focus HighlightRegion 1 2 Focus Highlight Region# border1.pyannCharles@tom.com 126 , 152 Python
  • 135. §4.5 Widgetfrom 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() 4-3 4-3: border1.pyannCharles@tom.com 127 , 152 Python
  • 136. Tkinter highlightcolor highlightbackground§4.5.5 cursor option widget option widget master widget cursor option Text Entry widget cursor option#!/usr/bin/env pythoncursors =["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 = 0for i in cursors: b=Button(text=i) b.grid( column=col,row=row, sticky=E+S+W+N) b.bind("<Motion>",lambda e,cur=i:root.config(cursor=cur)) col = col + 1 if col == 4 : row = row + 1 ; col = 0annCharles@tom.com 128 , 152 Python
  • 137. §4.5 Widgetmainloop() 4-4 4-4: cursor1.pyannCharles@tom.com 129 , 152 Python
  • 138. Tkinter§4.6 WM widget widget w.bind(event,handler) w widget, event handler callable§4.6.1# File: bind1.pyfrom Tkinter import *root = Tk()def callback(event): print "clicked at", event.x, event.ydef test(e): D = vars(e); for k in D: print "%-10s:%s"%(k,D[k])frame = Frame(root, width=100, height=100)frame.bind("<Button-1>", callback)root.bind("<Control-Alt-Key-colon>",test);frame.pack(expand=1,fill=BOTH)frame.focus_set()root.mainloop() callback Frame Control Alt ”¡Button-1¿” : <modifier-modifier-type-detail>annCharles@tom.com 130 , 152 Python
  • 139. §4.6 X windows 5 1 2 3 4 5 1,2,3 xmodmap xmodmap -pp xmodmap X xev modifier control alt win(super) 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 Meta Alt xmodmap X modifier <Control-Alt-Key-colon> Control Alt modifier Key type colon detail Control Alt Control Alt Shift Shift Double type ButtonPress ButtonRelease KeyPress KeyReleaseannCharles@tom.com 131 , 152 Python
  • 140. Tkinter man -S n bind type ButtonPress Button Release detail 1, 2, 3, 4, 5 detail modifier type <Button1> <Button-1> type Motion B1 modifier <B1-Motion> modifier type KeyPress KeyRelease detail keysyms man keysyms keysyms ASCII ASCII ASCII <1> <2> <3> <a> <b><c> ... a, b, c 4.6-2§4.6.2 event def test(event): D = vars(event); for k in D: print "%-10s:%s"%(k,D[k]) 4.6-3§4.6.3 • widget instance widget instance widget w.bind(...) w widget instanceannCharles@tom.com 132 , 152 Python
  • 141. §4.6 <Button-1> <1> <B1-Motion> <ButtonRelease-1> <Double-Button-1> ( ) ( ) <Enter> Widget Enter type <Leave> Widget <Return> <KeyPress-Return> keysyms <Key> a “a” <Shift-Up> Shift <Configure> Widget 4.6-2: widget widget event x,y widget pixel x root, y root char string keysym num wight, height widget configure type 4.6-3:annCharles@tom.com 133 , 152 Python
  • 142. Tkinter • widget Toplevel root root.bind(...) top.bind(...) root top Toplevel root • widget class bind_class class instance • bind_all bind_all F1 F1 ? <Key> <Return> <Return> <Key> Tkinter <Return> <Key> <Return> <Key> A B A B widget instance <key> toplevel <Return> Tkinter widget instance widget class Toplevel bind level.py# File: bind_level.pyfrom Tkinter import *root = Tk()def callback(event):annCharles@tom.com 134 , 152 Python
  • 143. §4.6 print "clicked at", event.x, event.ydef test(e): print "you press: " + e.keysym returndef 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 aframe = Frame(root, width=100, height=100)root.bind("<Key>", toplevel_bind)root.bind_class("Frame","<Key>",class_level_bind)root.bind_all("<Key>",application_level_bind)frame.bind("<Key>", widget_level_bind)frame.bind("<Return>", lambda e: myprint("RETURN PRESSED") )frame.pack(expand=1,fill=BOTH)frame.focus_set()root.mainloop()§4.6.4 bind(e,func) func “add” : bind(e,func,"add") “break”annCharles@tom.com 135 , 152 Python
  • 144. Tkinter change text bind.py# change_text_bind.pyfrom Tkinter import *def ignore (e): return "break"def ignore2(e): print "you can only input one line"root = Tk()t = Text()t.bind("<Return>",ignore2)t.bind("<Return>",ignore,"add")t.pack(fill=BOTH,expand=1)root.mainloop() Text widget ignore2 instance <Return> class ignore ignore2 “break” “break” root.bind_class("Text","<Return",ignore) Text widget Text§4.6.5 WM WM ( ) WM_DELETE_WINDOW WM w.protocol("WM_DELETE_WINDOW",handler) w widget handle :from Tkinter import *from tkMessageBox import askokcancelannCharles@tom.com 136 , 152 Python
  • 145. §4.7 Widgetdef handler(): if askokcancel("Quit","Do you really want to exit?"): root.destroy()root=Tk()root.protocol("WM_DELETE_WINDOW",handler)root.mainloop() WM_DELETE_WINDOW destroy WM_DELETE_WINDOW ICCCM(Inter-Client CommunicationConventions Manual)§4.7 Widget§4.7.1 root=Tk() root window Toplevel Toplevel root window Toplevel Widget pack grid WM “Tk” root.Title("My title") print root.Title()§4.7.2 menubar2.py# menubar2.pyfrom Tkinter import *import sysroot = Tk()annCharles@tom.com 137 , 152 Python
  • 146. Tkintermainmenu=Menu(root)root["menu"]=mainmenufilemenu = Menu(mainmenu)mainmenu.add_cascade(label=’file’,menu=filemenu)m = [ "new","open","save"]for i in m : filemenu.add_command( label=i, command=lambda t = i: sys.stdout.write(t+"n") )filemenu.add_command(label="exit", command= root.quit)mainloop() 4-5 4-5: menubar2.py lambda : sys.stdout.write(i) i i lambda t = i : sys.stdout.write(i)annCharles@tom.com 138 , 152 Python
  • 147. §4.7 Widget lambda widget Menubutton menubar3.py# menubar3.pyfrom Tkinter import *import sysroot = Tk()# create a frame to contain the menu barmenuframe = Frame()# create a menu buttonfilemenuButton = Menubutton(text="File")filemenuButton.pack(side=LEFT,anchor=N)# create the "file" menufilemenu = Menu(filemenuButton)# connect the filemenu with hte filemenuButtonfilemenuButton[’menu’]=filemenum = [ "new","open","save"]for i in m : filemenu.add_command(label=i, command= lambda t = i: sys.stdout.write(t+"n") )filemenu.add_command(label="exit", command= root.quit)menuframe.pack(side=TOP,fill=X,expand=1)mainloop() 4-6 Menubutton Button command Menubutton : 1. Menubutton. mb = Menubutton()annCharles@tom.com 139 , 152 Python
  • 148. Tkinter 4-6: menubar3.py 2. mb["text"]="press me" 3. Menu master widget mb m = Menu(mb) 4. Menu Menubutton mb["menu"] = m 5. menu m.add_command(label="new", command=lambda : sys.stdout.write("Hello Menun") 6. Menubutton mb.pack() menu m.add_separator() menu submenu = Menu(m) # master widget m.add_cascade(menu=submenu,label="a submenu")annCharles@tom.com 140 , 152 Python
  • 149. §4.7 Widget§4.7.3 Frame Button toolbar.py# toolbar1.pyfrom Tkinter import *root = Tk()def callback(): print "called the callback!"x = ["error","gray12","gray25","gray50","gray75","hourglass","info","question","warning"]# create a toolbartoolbar = Frame(root)for i in x : b = Button(toolbar, text=i, bitmap=i, command=lambda t=i: sys.stdout.write("%sn"%t) ) b.pack(side=LEFT, padx=2, pady=2,fill=BOTH,expand=1)toolbar.pack(side=TOP, fill=X)mainloop() 4-7 Button XY Button 2 toolbar : X bitmap otption image option PhotoImage§4.7.4 Frame LabelannCharles@tom.com 141 , 152 Python
  • 150. Tkinter 4-7: toolbar1.py statusbar.py# toolbar1.pyfrom Tkinter import *root = Tk()def callback(): print "called the callback!"x = ["error","gray12","gray25","gray50","gray75","hourglass","info","question","warning"]# create a toolbartoolbar = Frame(root)for i in x : b = Button(toolbar, text=i, bitmap=i, command=lambda t=i: sys.stdout.write("%sn"%t) )annCharles@tom.com 142 , 152 Python
  • 151. §4.7 Widget b.pack(side=LEFT, padx=2, pady=2,fill=BOTH,expand=1)toolbar.pack(side=TOP, fill=X)mainloop() tkSimpleStatus.py# File: tkSimpleStatusBar.pyfrom Tkinter import *class StatusBar(Frame): def __init__(self, master): Frame.__init__(self, master) self.label = Label(self, bd=1, relief=SUNKEN, anchor=W) self.label.pack(fill=X) def set(self, format): self.label.config(text=format) self.label.update_idletasks() def clear(self): self.label.config(text="") self.label.update_idletasks() 4-8 4-8: statusbar1.py Label§4.7.5annCharles@tom.com 143 , 152 Python
  • 152. Tkinter tkMessageBox Windows tkMessageBox.py Tk python /usr/lib/python2.2/lib-tk/tkMessageBox.py : showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, askretryignore. tkMessageBox.function(title, message [, options]). title message option : default ABORT, RETRY, IGNORE, OK, CANCEL, YES, NO icon ERROR, INFO, QUESTION, WARNING message message parent title title type ABORTRETRYIGNORE, OK, OKCANCEL, RETRYCANCEL, YESNO, YESNOCANCEL typeannCharles@tom.com 144 , 152 Python
  • 153. §4.7 Widget tkSimpleDialg tkSimpleDialog.askstring(title, prompt,[options]) Cancel None title prompt options initialvalue parent tkSimpleDialog.askinteger tkSimpleDialog.askfloat Cancel None option minvalue maxvalue tkFileDialog : tkFileDialog.askopenfilename tkFileDialog.asksavefilename Cancel None : tkFileDialog.askopenfilename(options) tkFileDialog.asksavefilename(options) option :annCharles@tom.com 145 , 152 Python
  • 154. Tkinter defaultextension string filetypes list list (label,pattern) tuple label pattern initialdir string initialfile string parent widget title string : openfile(filetypes=[("text file","*.txt")]) txt tkColorChooser askcolor : askcolor([color[,options]]) options : color “#rgb” “#rrggbb” “#rrrrggggbbbb” tuple RGB parent title tuple tuple x tkSimpleDialog Dialog tkSimpleDialog.pyannCharles@tom.com 146 , 152 Python
  • 155. §4.7 Widget Dialog Toplevel inputpassword.py#inputpassword.pyfrom Tkinter import *from tkSimpleDialog import *class DlgInputPassword(Dialog): def body(self,master): Label(master,text="user name:").grid(row=0,column=0) Label(master,text="password :").grid(row=1,column=0) self.username = Entry(master) self.username.grid(row=0,column=1) self.password = Entry(master) self.password.grid(row=1,column=1) def apply(self): self.result = self.username.get() , self.password.get() def validate(self): return 0root = Tk()d=DlgInputPassword(root)print d.result 4-9 4-9: inputpassword.py body apply body widget OK CancelannCharles@tom.com 147 , 152 Python
  • 156. Tkinter apply self.result OK apply self.result Cancel self.result None validate() validate() OK 1 apply self.result 0 OK buttonbox OK Cancel OK self.ok Cancel self.cancel self.ok self.cancel tkSimpleDialog.pyannCharles@tom.com 148 , 152 Python
  • 157. Python§5.1 C C$ls # demo.cspammodule.c$cat spammodule.c#include <Python.h> /* */static PyObject * /* Python .*/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 PyMethodDefSpamMethods[] = { {"system", spam_system, METH_VARARGS, "Execute a shell command."}, {NULL, NULL, 0, NULL} /* */};void initspam(void){annCharles@tom.com 149 , 152 Python
  • 158. Python Py_InitModule("spam", SpamMethods);} module spam spam.system(cmd) os.system initspam(...) spam_system(...) SpamMethords initspam import init + module_name module spam main python spam Py_InitModule "spam" module SpamMethords python spam SpamMethors PyMethodDef PyMethordDef • python system python spam.system • spam_system static PyObject * spam_system(PyObject * self, PyObject * args); METH_VARARGS • doc string python spam.system.__doc__ • (macro) C Python tuple METH_VARARGS dictionary keyword parameter METH_VARARGS|METH_KEYWORDS Macro C spam_system Python “ ” C PyObject* PyObject* C NULL spam_system PyObject* • self NULL class methord self class instance • args tuple tuple C PyObject*annCharles@tom.com 150 , 152 Python
  • 159. §5.1 C PyArg_ParseTuple args "s" s string "s" "s" char** Python PyArg_ParseTuple command NULL PyArg_ParseTuple system C system sts Py_BuildValue() python PyObject* "i" integer NULL Python Python Python Python module C module Python Python Unix Modules/Setup.localspam spammodule.o spammodule c Modules Python Python C distutils package setup.py$lssetup.py spammodule.c$cat setup.pyfrom distutils.core import setup, Extensionmodule1 = Extension(’spam’, sources = [’spammodule.c’])setup (name = ’spam package’, version = ’1.0’, description = ’This is a spam package’, ext_modules = [module1]) distulis$python setup.py build #running buildrunning build_extannCharles@tom.com 151 , 152 Python
  • 160. Pythonbuilding ’spam’ extensioncreating buildcreating build/temp.linux-i686-2.2gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.2 -c spammodule.c -o build/temp.linux-i686-2.2/spammodule.ocreating build/lib.linux-i686-2.2gcc -shared build/temp.linux-i686-2.2/spammodule.o -o build/lib.linux-i686-2.2/spam.so$$ls # buildbuild setup.py spammodule.c$cp build/lib.linux-i686-2.2/spam.so . #$python # pythonPython 2.2 (#1, Apr 12 2002, 15:29:57)[GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import spam # module>>> print spam.system.__doc__ # DOC stringExecute a shell command.>>> print spam.system("echo ’hello’") #hello #ok,0 # spam.system>>>annCharles@tom.com 152 , 152 Python