Professional Documents
Culture Documents
org/book/export/html/166
สําหรับลินุกซดิสโทรอื่นก็คลาย ๆ กัน
1 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ทั้งหมดนี้เปนการเรียกใชตัวแปลบรรทัดคําสั่งของไพธอน ซึ่งจะทําใหเราสามารถใชงานแบบโตตอบกับตัวแปลภาษา
ได
ถาอยูในโหมดโตตอบ ไพธอนจะกลับสูพร็อมตหลัก
ถาอยูในโหมดทํางานจากไฟล ไพธอนจะออกมาดวยตัวเลขรายงานสถานะที่ไมใชศูนย (ถาเปนศูนยคือไมเกิด
ขอผิดพลาด)
2 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
อยาลืมเปลี่ยนโหมดใหรันไดดวย
$ chmod +x myscript.py
currency = u"€"
print ord(currency)
3 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> (50-5*6)/4
5
>>> 7/-3
-3
กําหนดคาใหตัวแปรดวย = ตามปกติ
>>> width = 20
>>> height = 5*9
>>> width * height
900
กําหนดคาทีละหลายตัวแปรพรอมกันก็ได
>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
>>> 7 / 2
3
4 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> 7.0 / 2
3.5
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
>>> a.imag
0.5
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> price + _
113.0625
>>> round(_, 2)
113.06
5 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
ใชสตริงแบบหลายบรรทัด โดย...
6 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
สตริงในไพธอนไมเหมือนกับภาษาซี ไพธอนไมสามารถเปลี่ยนคาสตริงโดยอางจากดัชนีได
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
แตก็สรางใหมไดไมยาก
>>> 'x' + word[1:]
'xelpA'
>>> x = word[:]
>>> x = 'Splat' + x[4]
>>> x
'SplatA'
7 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> word[10:]
''
>>> word[2:1]
''
ดัชนีที่เปนคาลบ จะเปนการนับจากขวามาซาย
>>> word[-1] # The last character
'A'
เราหาความยาวของสตริงไดดวยฟงกชัน len()
>>> s = 'supercalifragilisticexpialidocious'
8 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> len(s)
34
ดูเพิ่มเติม
เรื่อง
>>> str(u"abc")
'abc'
>>> u"äöü"
u'\xe4\xf6\xfc'
>>> str(u"äöü")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2:
ordinal not in range(128)
9 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
การใชดัชนีในการอางถึงขอมูลยอยภายใน ใชงานคลายกับสตริง
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
แตตางจากสตริงตรงที่ขอมูลยอยภายในสามารถเปลี่ยนแปลงคาได โดยการอางจากดัชนี
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = 10
>>> a
['spam', 'eggs', 10, 1234]
กําหนดคาเปนชวงสไลซก็ได
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
10 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> # Clear the list: replace all items with an empty list
... a[:] = []
>>> a
[]
ซอนลิสตในลิสตก็ได
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> q
[2, 3, 'xtra']
ความรูใหม
11 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ใช , หากไมตองการขึ้นบรรทัดใหม
>>> a, b = 0, 1
>>> while b < 1000:
... print b,
... a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
มี elif กี่ตัวก็ได และมี else หรือไมมีก็ได (ภาษาอื่นอาจมี switch และ case แตไพธอนใช if อยางเดียว)
12 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ใชสรางลิสตจากชวงของตัวเลขจํานวนเต็ม
แบบงาย
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
อาจกําหนดเปนชวง
>>> range(5, 10)
[5, 6, 7, 8, 9]
หรือแบบกําหนดขนาดขั้นของการเพิ่มดวย
>>> range(0, 10, 3)
[0, 3, 6, 9]
4.4 คําสั่ง break และ continue และวลี else สําหรับการวนรอบ (break and continue Statements, and else
Clauses on Loops)
13 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
เอาตัวอยางในการเขียนอนุกรมฟโบนัชชีมาเขียน
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while b < n:
... print b,
... a, b = b, a+b
...
14 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ชื่อฟงกชันสามารถถูกกําหนดคาใหกับตัวแปรได
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
>>> f
<function fib at 10042ed0>
จากตัวอยางขางตน สามารถเขียนในรูปฟงกชันที่สงคืนคาดังนี้
>>> def fib2(n): # return Fibonacci series up to
... """Return a list containing the Fibonacci series up to n.""
... result = []
... a, b = 0, 1
... while b < n:
... result.append(b) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
ความรูใหม
มีหลักในการกําหนดคาอารกิวเมนตคือ
15 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
การใชงานเชน ask_ok('Do you really want to quit?') หรือ ask_ok('OK to overwrite the file?', 2,
'Please answer y or n')
ขอควรระวัง
>>> i=6
>>> f()
5
การใชงาน
แบบนี้ใชได
16 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
แบบนี้ผิด
parrot() # ผิดเพราะขาดคาที่ไมมีคาปริยาย คือ voltage
parrot(voltage=5.0, 'dead') # ผิดเพราะคาปริยายอยูซาย จริง ๆ ตองอยูขวา
parrot(110, voltage=220) # ผิดเพราะกําหนดคาซอน
parrot(actor='John Cleese') # ผิดเพราะชื่อไมมีชื่อคียเวิรด actor
ตัวอยางการรายงานขอผิดพลาดของการกําหนดคาซอน
>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: function() got multiple values for keyword argument 'a'
ตัวอยางคือ
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
print '-'*40
keys = keywords.keys()
keys.sort()
for kw in keys: print kw, ':', keywords[kw]
เรียกใชดวยคําสั่ง
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
ในที่นี้
ผลลัพธคือ
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
17 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ความรูใหม
หากเราสงผานอารกิวเมนตแบบอางอิงซึ่งจะกลายเปนทูเปลแลว เราจะไดความยืดหยุนในการกําหนดอารกิวเมนต
ตัวอยางคือ
>>> def testparm(x, *y):
... print 'x=',x,'y=',y
...
>>> testparm('a',1,2,3)
x= a y= (1, 2, 3)
หรือ
>>> def testparm(x, *y):
... print 'x=', x, 'y=',
... for i in y:
... print i,
...
>>> testparm('a',1,2,3)
x= a y= 1 2 3
ตัวอยางในบทความตนฉบับคือ
def fprintf(file, format, *args):
file.write(format % args)
ตัวอยางนี้เปนดิกชันนารี
>>> def parrot(voltage, state='a stiff', action='voom'):
... print "-- This parrot wouldn't", action,
... print "if you put", voltage, "volts through it.",
... print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
18 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
โครงสรางชวนเวียนหัวหนอย ดูตัวอยางดีกวา
แบบไมใช lambda
>>> def f(x):
... return x*2
...
>>> f(3)
6
อีกตัวอยางนึง ใชผสมกับฟงกชัน
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
สามารถเรียกดูขอความในบรรทัดนี้ไดจากเมธอด function_name.__doc__
ตัวอยาง
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
19 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
บทนี้จะอธิบายเทคนิคการใชงานขอมูล
append(x)
เติมสมาชิกตอทายลิสต มีคาเทียบเทา a[len(a):] = [x]
>>> a=[1,2,3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
extend(L)
ยกลิสต L ทั้งยวง ไปขยายตอทาย a คือ a[len(a):] = L
>>> a=[1,2,3]
>>> L=[4,5,6]
>>> a.extend(L)
>>> a
[1, 2, 3, 4, 5, 6]
insert(i, x)
แทรกสมาชิก x ในตําแหนง i
a.insert(0, x) ก็คือการไปแทรกขางหนา
a.insert(len(a), x) ก็คือการไปตอทาย คือ a.append(x)
>>> a=[1,2,3]
>>> a.insert(2,0)
>>> a
[1, 2, 0, 3]
remove(x)
ลบสมาชิกตัวแรกที่มีคาเทากับ x ถาไมมีเทาจะเกิดขอผิดพลาด
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a.remove(2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: list.remove(x): x not in list
pop([i])
ถอดสมาชิกในตําแหนง i ออก ถาละเลยไมใสคา i จะถอดตัวสุดทายออกแทน
20 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> a=[1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
index(x)
คืนคาดัชนีของลิสต ตัวที่มีคาเทากับ x ถาไมมีคาเทาเลยจะแจงความผิดพลาด
>>> a=[1,2,3]
>>> a.index(2)
1
count(x)
นับจํานวนสมาชิกที่มีคาเทากับ x
>>> a=[2,2,2,9,4,4,4,4]
>>> a.count(2)
3
sort()
จัดเรียงสมาชิก
>>> a=[1,5,4,2,3]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
reverse()
กลับตําแหนงสมาชิก
>>> a=[1,5,4,2,3]
>>> a.reverse()
>>> a
[3, 2, 4, 5, 1]
ตัวอยางรวมอีกทีนึง
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
21 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']
filter(function, sequence)
filter จะกรองขอมูลนําเขาใน sequence โดยเอาเฉพาะตัวที่ทําให function คืนคาจริง (ไมใชศูนยหรือ None)
ไว งงนิดหนอย ดูตัวอยางดีกวา เปนการหาจํานวนเฉพาะ
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
map(function, sequence)
map จะเขาใจงายกวา คือจะเอาคาจาก sequence ไปทํางานใน function แลวคืนผลลัพธออกมาเปนลิสต
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
22 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> s2 = range(10,18)
>>> map(add, seq, s2)
[10, 12, 14, 16, 18, 20, 22, 24]
reduce(function, sequence)
เอาขอมูลสองตัวแรกของ sequence ไปเรียก function ซึ่งเปนฟงกชันที่รับอารกิวเมนตสองตัว จากนั้นเอา
ผลลัพธที่ไดกับขอมูลถัดไปใน sequence ไปเรียก function ตอ ๆ ไปจนหมดขอมูล
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
เพื่อเปนการปองการการผิดพลาดดังกลาว อาจใสอารกิวเมนตตัวที่สามซึ่งจะกลายเปนคาเริ่มตนใหกับ
function เพื่อปองกันกรณีลิสตวาง ดังนี้
>>> xsum([])
0
ตัวอยาง
23 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> [x, x**2 for x in vec] # error - parens required for tuples
File "<stdin>", line 1, in ?
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
24 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> t
(12345, 54321, 'hello!')
>>> singleton
('hello',)
และแนนอนวาใชกับลิสตไดเชนเดียวกัน
[x, y, z] = t
25 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
True
เปลี่ยนแปลงคาได
key อาจเปนขอมูลชนิดสตริง ตัวเลข หรือทูเปลที่ไมไดบรรจุ mutable object ไว
ลิสตใชเปนคียไมได เพราะมันเปลี่ยนคาภายในได
ลบคาภายในไดดวยประโยค del
ถาใสคาคียซ้ํา จะแทนที่คาเกา
ถาคนคียที่ไมมีอยู จะแสดงขอผิดพลาด
ใชเมธอด keys() ในการแสดงคาคียทั้งหมด และใชเมธอด has_key() ในการคนคาคีย
สมาชิกภายใน จะไมมีการเรียงลําดับตามคาของคีย
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
True
แปลงทูเปลในลิสตมาเปนดิกชันนารีดวยฟงกชัน dict()
26 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
iteritems()
ใชแตกคาคูของดิกชันนารี
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
enumerate()
ใชแปลงจากลิสต (หรือทูเปล) มาเปนดิกชันนารี ที่มีคาคียเปนตัวเลข
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
zip()
ใชจับคูสองอนุกรม (ลิสตหรือทูเปลหรือผสมกัน) ที่มีจํานวนสมาชิกเทากัน แปลงรูปมาใชงานแบบดิกชันนารี
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print 'What is your %s? It is %s.' % (q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
reversed()
ใชกลับคาสมาชิก
>>> for i in reversed(xrange(1,10,2)):
... print i
...
9
7
5
3
1
sorted()
ใชจัดเรียงสมาชิก
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
27 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
... print f
...
apple
banana
orange
pear
>>> True == 1
True
>>> 1 < 2 == 1
False
>>> 1 < 2 == 2
True
ตัวกระทําทางตรรกะ มีความสําคัญนอยที่สุด โดย not สําคัญที่สุด และ or สําคัญนอยที่สุด เชน A and not B
or C มีความหมายเทากับ (A and (not B)) or C
ตัวกระทําทางตรรกะ จะกระทําจากซายไปขวา และถาจุดใดที่เมื่อคํานวณแลวสามารถระบุผลลัพธของทั้ง
นิพจนไดโดยไมตองเปรียบเทียบตอ ก็จะไมคํานวณนิพจนสวนที่เหลือ ไพธอนเรียกการนี้วา ตัวกระทําลัดวงจร
(short-circuit operators) และคาที่คืนออกมาจากการเปรียบเทียบ จะเปนคาสุดทายที่ทําการเปรียบเทียบ
สามารถกําหนดคาผลของการเปรียบเทียบ ใหกับตัวแปรได
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
6. มอดูล (Modules)
28 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
เริ่มตนใชงานวา
>>> import fibo
เรียกใชงานฟงกชันโดย
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
เพื่อใหกระชับ เราสามารถกําหนดคาตัวแปรแทนเมธอดในมอดูลได
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
29 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
เขียนรูปแบบการอิมพอรตไดหลากหลาย
เลือกอิมพอรตบางฟงกชัน
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
จะหาที่ไดเรกทอรีปจจุบันกอน
ถาไมพบจะไปหาจากคาในตัวแปรแวดลอม PYTHONPATH
ตามดวยพาธของไพธอนเอง สําหรับเดเบียนคือ /usr/lib/python2.4 (ตัวเลข 2.4 จะเปลี่ยนไปตามรุนไพ
ธอนที่ใช)
สําหรับเซียน
30 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'callstats', 'copyright',
'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions']
31 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
เรียกใชไดสองแบบ
32 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ถาไมมี as
import Sound.Effects.echo
เวลาอางถึงตองอางแบบเต็ม ๆ
Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
ถามี as
import Sound.Effects.echo as SEe
อางถึงโดยใชชื่อยอ
SEe.echofilter(input, output, delay=0.7, atten=4)
หรือถาอิมพอรตเจาะเฉพาะฟงกชัน ก็เรียกเฉพาะฟงกชัน
from Sound.Effects.echo import echofilter
echofilter(input, output, delay=0.7, atten=4)
หมายเหตุ
มีหลักอยูวา
33 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
import echo
echo.echofilter(input, output, delay=0.7, atten=4)
หรือ
from echo import echofilter
echofilter(input, output, delay=0.7, atten=4)
ถาอยูลึกลงไป สามารถเรียกผานจากระดับเดิมไดทันที
นอกเหนือจากนี้ ตองอางอิงแบบเต็มยศ เหมือนการเรียกจากมอดูลจากแพกเกจอื่น
*** เวนแตไพธอนรุน 2.5 ขึ้นไป จะสามารถเรียกยอนขึ้นไดดวย ตัวอยางการเรียกคือ
from . import echo
from .. import Formats
from ..Filters import equalizer
>>> repr(s)
"'Hello, world.'"
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.10000000000000001'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print s
The value of x is 32.5, and y is 40000...
34 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
'hello, world\n'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
เทียบกับการใช %
>>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
อีกอันนึงเปนการจัดชิดขอบซายขวาดวย %
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '%-10s ==> %10d' % (name, phone)
...
Jack ==> 4098
35 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
mode มีคาไดดังนี้
f.read([ size ])
ถาไมระบุขนาดไบตหรือขนาดเปนลบ เขาจะอานทั้งไฟล ถาอานไฟลจนหมดแลว จะคืนคาเปนอักขระวาง ("")
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
f.readline()
อานหนึ่งบรรทัด คืออานจนพบอักขระ \n ถาอานไฟลจนหมดแลว จะคืนคาเปนอักขระวาง ("")
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
f.readlines()
36 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
อานทั้งไฟลโดยแยกแตละบรรทัดเปนแตละสมาชิกในลิสต
>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']
for line in f:
อันนี้ไมใชเมธอด แตเปนประโยคการเขียนแบบพิเศษ ที่ใชเปนปกติในไพธอน อานโคดงาย และเหมาะสมใน
การใชงานจริง
>>> for line in f:
print line,
This is the first line of the file.
Second line of the file
f.write(string)
เขียนสตริงกลงไฟล คืนคาเปน None
>>> f.write('This is a test\n')
ถาขอมูลไมไดอยูในรูปสตริง ตองแปลงกอน
>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
f.tell()
ใชบอกตําแหนงปจจุบันของไฟล นับจากตนไฟล
f.seek(offset [, from_what])
ใชตั้งตําแหนงที่จะอานเขียนไฟล offset คือจํานวนไบต from_what คือตําแหนงอางอิง
0 หรือ ไมใส คือเทียบจากตนไฟล
1 คือ จากตําแหนงปจจุบัน
2 คือ จากทายไฟล
>>> f = open('/tmp/workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5) # Go to the 6th byte in the file
>>> f.read(1)
'5'
f.close()
ปดการทํางานกับไฟลนั้น ถาปดแลวกลับมาอานอีกจะเกิดขอผิดพลาด
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
เปนการเก็บออบเจกตลงไฟลแบบไรขอจํากัด ดูเรื่องปกเกิลในบรรณสารของไพธอน
37 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
คือ
pickle.dump(x, f)
เวลานํากลับก็ใชวา (f ตองถูกเปดอยูกอนแลว)
x = pickle.load(f)
มือใหมตองเจอทุกคน
>>> while True print 'Hello world'
File "<stdin>", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax
ขอผิดพลาดแบบนี้ตองตามไปแกในโคดอยางเดียว
เกิดตอนรัน
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
38 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
บรรทัดสุดทายเปนการบอกวาผิดเรื่องอะไร
ตัวอยางขางลางเปนการจัดการสิ่งผิดปรกติ โดยจะจัดการดูเฉพาะคาที่เราปอนเขาไปวาถูกตองหรือไม
(ValueError) แตถาเปนสิ่งผิดปรกติแบบอื่น โปรแกรมจะปลอยใหเปนหนาที่ของระบบ จึงทําใหเราสามารถใชปุม
Ctrl-C ในการตัดการทํางานของโปรแกรมได ซึ่งกรณีตัดการทํางานนี้จะเปนสิ่งผิดปรกติแบบ KeyboardInterrupt
เราระบุสิ่งผิดปรกติไดหลายแบบในครั้งเดียว
... except (RuntimeError, TypeError, NameError):
... pass
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
39 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> try:
... raise Exception('spam', 'eggs')
... except Exception, inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'instance'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
เราสามารถปาวสิ่งผิดปรกติเมื่อพบได เชน
>>> raise NameError, 'HiThere'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
40 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
ดูเรื่องคลาสไดในบทตอไป
41 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
9. คลาส (Classes)
42 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
เพื่อใหเกิดความสุขสวัสดีทั้งผูเขียนและผูอาน บทนี้จะใชทับศัพทใหมากที่สุดเทาที่เปนไปได :)
ศัพทสนุก ๆ
เนมสเปซ (Namespace)
เปนรายชื่อของออบเจกตทั้งหมดในขอบเขตหนึ่ง ๆ เนมสเปซมีหลายระดับ ตั้งแตของทั้งโปรแกรมมาจนถึงเนม
สเปซภายในออบเจกต ในทางปฏิบัติแลวไพธอนเก็บไวในรูปดิกชันนารี ตัวอยางของเนมสเปซคือ กลุมของชื่อ
บิลตอิน (Built-in Names = built-in function + built-in exception) จะอยูภายใตเนมสเปซเดียวกัน หรือ ชื่อสวน
รวม (Global Names = global function + global exception + global variables) ตาง ๆ ของมอดูล ก็จะอยูในเนม
สเปซของมัน การมีเนมสเปซทําใหออบเจกตตางเนมสเปซกันไมตีกันถึงแมจะชื่อเดียวกัน เวลาเราอางถึงออ
บเจกตที่อยูลึกลงไป เราจึงตองอางตามรายแอตทริบิวต
43 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
แอตทริบิวต (Attribute)
ก็คือชื่อที่อยูภายในเนมสเปซหนึ่ง ๆ อางดวยเนมสเปซ ตามดวยจุด (.) ตามดวยชื่อแอตทริบิวต เชน z.real
เราเรียก real วาเปนแอตทริบิวตของออบเจกต z อะไรก็ตามที่อยูในระดับเดียวกับ real คืออางถึงดวย z.XXX
เราจะเรียกวาอยูภายใตเนมสเปซเดียวกัน (ถาชื่อซ้ําก็ตีกัน)
สโคป (Scope)
หมายถึงชวงที่เนมสเปซสามารถเขาถึงไดโดยตรง โดยไมตองอางอิงไลแอตทริบิวตไปถึงออบเจกตที่อยูใน
เนมสเปซอื่น
เรื่องสนุก ๆ
--รอแปล--
โครงคือ
class ClassName:
<statement-1>
.
.
.
<statement-N>
--รอแปล--
จะใชงานหรือเขาถึงคลาสออบเจกตไดสองแบบ คือ
44 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
class MyClass:
"A simple example class"
i = 12345
def f(self):
return 'hello world'
เราสามารถเขาถึงคลาสนี้ดังนี้
>>> MyClass.i
12345
>>> MyClass.f
<unbound method MyClass.f>
>>> MyClass.__doc__
'A simple example class'
>>> MyClass.i = 2
>>> MyClass.i
2
การสรางอินสแตนซ (instantiation)
ใชรูปแบบธรรมชาติเหมือนกับการสรางฟงกชัน
x = MyClass()
เปนการสรางอินสแตนซซึ่งเปนออบเจกตที่ถูกบรรจุอยูในตัวแปร x
45 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
เมธอด (Method)
ก็คือฟงกชันของอินสแตนซออบเจกตนั่นเอง จากตัวอยาง x.f คือเมธอดของอินสแตนซ สวน MyClass.f คือ
ฟงกชันของคลาส
เราอาจอางถึงเมธอดผานตัวแปรได
xf = x.f
while True:
print xf()
class C:
f = f1
def g(self):
46 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ถาสืบทอดไมไดก็ไมใชคลาส รูปแบบโครงสรางของการสืบทอดคือ
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
ถาคลาสฐานถูกกําหนดไวที่มอดูลอื่น รูปแบบจะเปน
class DerivedClassName(modname.BaseClassName):
รูปแบบโครงสรางคือ
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
47 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> a.__spam
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute '__spam'
>>> dir(a)
['_C__spam', '__doc__', '__module__', 's']
อาจเติมแอตทริบิวตขอมูลใหกับคลาสอินสแตนซไดทุกเมื่อ
class Employee:
pass
ดังนั้น เราสามารถสรางตัวยกขอผิดพลาดแบบซอนลึกลงไปเรื่อย ๆ
เขียนไดสองรูปแบบคือ
raise Class, instance
อีกอันคือ
raise instance
ซึ่งถาเขียนแบบเต็ม ๆ ตองเขียนวา
48 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
เวลายกขอผิดพลาดขึ้นแสดง รูปแบบคือ
Exception_Class: str(instance)
ลองดูตัวอยาง for
for element in [1, 2, 3]:
print element
for element in (1, 2, 3):
print element
for key in {'one':1, 'two':2}:
print key
for char in "123":
print char
for line in open("myfile.txt"):
print line
เบื้องหนาก็ดูงาย ๆ ดี เราลองมาดูเบื้องลึกบาง
49 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> s = 'abc'
>>> it = iter(s)
>>> it
<iterator object at 0x00A1DB50>
>>> it.next()
'a'
>>> it.next()
'b'
>>> it.next()
'c'
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
it.next()
StopIteration
รันไดวา
>>> for char in Reverse('spam'):
... print char
...
m
a
p
s
รันไดวา
>>> for char in reverse('golf'):
50 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
51 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
os
มอดูล os มีเมธอดใหใชเยอะมาก
>>> import os
>>> os.system('time 0:02')
0
>>> os.chdir('/server/accesslogs')
>>> help(os)
<returns an extensive manual page created from the module's docstrings>
shutil
สําหรับงานจิปาถะเล็ก ๆ นอย ๆ อาจใชตัวนี้แทน ดูจะอานเขาใจงายกวา
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')
glob
ใชกับไวลดคารดคลองตัวกวา
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
sys
ใชเยอะมาก เชน สมมุติไฟล demo.py มีโคดแบบนี้
#!/usr/bin/env python
import sys
print sys.argv
52 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
10.4 นําเขา สงออก และเปลี่ยนทิศ (Error Output Redirection and Program Termination)
sys
ใช sys เหมือนเดิม เพราะในนี้มีฟงกชันของ stdin stdout และ stderr เราจะผันการแสดงผลลัพธไปทาง
ไหน ก็ใชจากมอดูลนี้
>>> sys.stderr.write('Warning, log file not found starting a new one
')
Warning, log file not found starting a new one
re
ใชงาน เรกูลารเอกเพรสชั่น (regular expression) ไดสะดวกและเปนธรรมชาติ
>>> import re
ใชเมธอดของสตริงที่มีอยูแลว
ถางานไมซับซอน ใชอันนี้เร็วกวา อานงายตรวจงาย
>>> 'tea for too'.replace('too', 'two')
'tea for two'
math
มอดูลนี้ ใชงานทศนิยมลอยและไลบรารีมาตรฐานทางคณิตศาตรไดคลองตัวกวา
>>> import math
>>> math.cos(math.pi / 4.0)
0.70710678118654757
>>> math.log(1024, 2)
10.0
random
งานการสุมแยกออกมาจาก math
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
53 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
urllib2
ใชงานดานลูกขาย (client) เชนเปดดู url เปนตน
>>> import urllib2
>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
... if 'EST' in line or 'EDT' in line: # look for Eastern Time
... print line
smtplib
ใชจัดการเมล
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org
>>> server.quit()
datetime
มอดูลนี้มีฟงกชันทางวันที่และเวลาเยอะ รวมทั้งยังรองรับเรื่องโซนเวลาดวย
# dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
54 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979
timeit
ใชจับเวลา ตัวอยางเปนการจับเวลาเทียบกันระหวางการสลับคาแบบโบราณ คือเอาตัวแปรชั่วคราวมาใช
สําหรับสลับ กับการสลับแบบใชทูเปลที่ไพธอนถนัด วาอันไหนเร็วกวา
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
สนุก ๆ นะครับ อันนี้เครื่องผม Intel Core2 Duo E6300 เริ่มเกาแลวละ ไพธอนรุน 2.4.4 [GCC 4.2.3 20071123
(prerelease) (Debian 4.2.2-4)]
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.21430277824401855
doctest
ใชตรวจสอบมอดูล โดยเราจะตองเขียนผลการทดสอบที่เราหวังวามันจะเปนแบบนั้นไวใน docstring เวลารัน
เขาก็จะทดสอบรันตามนั้น ถาผลตรงกันก็ใชได แตถาผลไมตรง ก็จะรายงานออกมา
def average(values):
"""Computes the arithmetic mean of a list of numbers.
55 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
import doctest
doctest.testmod() # automatically validate the embedded tests
unittest
ใชงานยากกวา แตดูเปนระบบใชไดจริงกวา
import unittest
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average([20, 30, 70]), 40.0)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
repr
มอดูล repr มีไวสําหรับปรับฟงกชัน repr() ใหเปนแบบที่เราตองการ
56 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
pprint
ชวยจัดรูปแบบใหเหมาะกับงานที่ไปออกเครื่องพิมพ
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
textwrap
เปนอีกตัวนึง แตเหมาะในการจัดการงานขอความ
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
locale
จัดรูปแบบออกมาใหเหมาะกับภาษาของประเทศที่เรากําหนด
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
string
เปนเรื่องการจัดการขอความใหเหมาะสม โดยถาเราเขียนโคดใหเรียกใชเทมเพลตแลว เวลาแจกจายโปรแกรม
ไปแลว ผูใชสามารถปรับแตงขอความใหเหมาะสมกับงานของเขาไดงายกวาตองมาแฮกโคดเอง
เวลาใชเอาเครื่องหมาย "$" ใสขางหนาตัวแปร แลวแทนคาตอนรัน (แตถาตองการใช $ ก็แคใสเปน "$$")
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
57 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
struct
มอดูลนี้ใชฟงกชัน pack() และ unpack() ในการทํางานกับขอมูลไบนารีที่มีความยาวไมคงที่ ตัวอยางจะเปน
การวนรอบทํางานกับขอมูลสวนหัวของไฟล ZIP (ใชสัญลักษณ "H" และ "L" แทนขอมูลไบนารีแบบไมนับ
เครื่องหมายขนาด 2 และ 4 ไบต ตามลําดับ)
import struct
start += 16
filename = data[start:start+filenamesize]
start += filenamesize
extra = data[start:start+extra_size]
print filename, hex(crc32), comp_size, uncomp_size
58 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
threading
ตัวอยางเปนการใชมอดูลนี้บีบอัดขอมูล โดยทําเปนงานเบื้องหลัง
import threading, zipfile
class AsyncZip(threading.Thread):
def __init__(self, infile, outfile):
threading.Thread.__init__(self)
self.infile = infile
self.outfile = outfile
def run(self):
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
f.write(self.infile)
f.close()
print 'Finished background zip of: ', self.infile
Queue
จากขอกังวลเรื่องการแลกเปลี่ยนขอมูลกับงานภายนอกนี่เอง จึงเกิดมอดูลนี้ขึ้นมา ทําใหเราไมตองมาเขียน
เรื่องจังหวะการรอของเธรดเอง
logging
มอดูลนี้มีเครื่องมือใหพรอมสําหรับการบันทึกปูม งายสุดคือการสงไปใหระบบแสดงคือ sys.stderr
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
ใหผลแบบนี้
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
59 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
นอกจากนี้ยังสามารถแยกทําเปนไฟลปรับตั้งสําหรับงานปูมโดยเฉพาะ โดยไมตองเขาไปยุงกับโคดหลักเลย
ปกติไพธอนจัดการหนวยความจําไดดีอยูแลว แตมีบางงานที่ยกเวน
weakref
งานตามรอยโคด (tracking) เราตองสรางตัวแปรอางอิงของเราขึ้นมา หลายครั้งตัวที่เราสรางกลับกลายเปน
ปญหาเสียเอง เวลาเราลบตัวแปรไมหมดมันจะไปรบกวนหนวยความจําที่เราตองการดู มอดูล weakref ทํามา
เพื่อการนี้โดยเฉพาะ
>>> import weakref, gc
>>> class A:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return str(self.value)
...
>>> a = A(10) # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a # does not create a reference
>>> d['primary'] # fetch the object if it is still alive
10
เพราะลิสตใชงาย เลยมีคนเขียนมอดูลเติมความสามารถใหใชไดหลายหลายยิ่งขึ้น
array
ใชแปลงลิสตเปนแอเรยออปเจคตที่เหมาะกับงานตัวเลข ตัวอยางเปนลิสตของตัวเลขที่เปนจํานวนเต็ม (ปกติ
ใชหนวยความจํา 16 ไบต) ถูกแปลงเปนแอเรยของขอมูลไบนารีไมคิดเครื่องหมายขนาด 2 ไบต (ใชสัญลักษณ
"H" แปลงแลว ใชงานงายมาก
>>> a[1:3]
array('H', [10, 700])
60 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
collections
มอดูลนี้มีออปเจคต deque() ที่ใชงานเหมือนลิสต ถาเพิ่มหรือลดสมาชิกขางหนาหรือตอทายแลวจะเร็วกวา
ลิสต แตถาแทรกหรือคนขอมูลจะชากวา เราเลยเอามาใชในงานคิว
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print "Handling", d.popleft()
Handling task1
bisect
ใชเรียงลิสต
>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
heapq
ใชจัดการฮีป จะเร็วกวาใชลิสตจริง ๆ เพราะงานฮีปเราสนใจแคคาตัวที่นอยที่สุดเทานั้น ไมตองจัดเรียงใหมทั้ง
ลิสต
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data) # rearrange the list into heap order
>>> heappush(data, -5) # add a new entry
>>> [heappop(data) for i in range(3)] # fetch the three smallest entries
[-5, 0, 1]
decimal
มอดูลนี้มีชนิดขอมูลชื่อ Decimal สําหรับเลขทศนิยมลอยที่เหมาะกับงานบัญชี และงานที่ตองการความถูกตอง
ของทศนิยมสูง
ตัวอยางเปนการคํานวณภาษีอัตรารอยละ 5 ของคาโทรศัพท 70 สตางค เทียบกันระหวางใช Decimal กับใช
ทศนิยมลอยของระบบ
>>> from decimal import *
>>> Decimal('0.70') * Decimal('1.05')
Decimal("0.7350")
ดูตัวอยางขอผิดพลาดจากการหาเศษผลหาร
61 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
และความผิดพลาดจากการจัดการตัวเลขในลิสต
>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
นอกจากนี้ ยังสามารถกําหนดความละเอียดของทศนิยมไดเทาที่เราตองการ
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal("0.142857142857142857142857142857142857")
13. ปจฉิมลิขิต
ยังเรียบเรียงไมหมด ยังขาดอีก 4 เรื่อง ที่ยังไง ๆ ก็ไมแปลเด็ดขาด เพราะทานที่อานจนมาถึงตรงนี้ไดก็คงเกงภาษา
อังกฤษกวาผมแลว :D
คือ
62 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ตัวอยางการใชไพธอนทําหองแสดงภาพผานเว็บ
ทําหองแสดงภาพผานเว็บดวยไพธอนอยางงาย
ความตองการคือ
เสร็จแลว
ถาเราเอาอะไรใสเขาในไดเรกทอรี่ /var/www/pythongal เขาจะจัดการลดขนาดภาพและสรางภาพเล็กใหเอง โดย
เก็บไฟลเหมือนระบบไฟลปกติ
ลองทดสอบหนาตัวอยางไดที่ www.thaitux.info/pythongal
และหนา admin สําหรับหมุนภาพที่ www.thaitux.info/.admin-pythongal
63 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
ปญหาคือตัวโปรแกรม ps2pdf ซึ่งไปเรียกใช ghostscript (gs) อีกทีนึง ไมสามารถ crop ขนาดจาก A4 เปน A5 ได
(จริง ๆ แลวอาจทําได แตคนคําสั่งไมพบ และโรงพิมพตองการงานขนาด A5 แบบมีขอบขาวเวนไวดานละ 3 มม. ซึ่ง
คงจะใชคําสั่ง gs ยาก)
เริ่มเลยแลวกัน
ติดตั้งมอดูล pyPdf
$ sudo aptitude install python-pypdf
#!/usr/bin/env python
#prerequisites: aptitude install python-pypdf
import sys
import pyPdf
def usage(progname):
print """
usage: %s "lowerLeft-x lowerLeft-y upperRight-x upperRight-y" infile.pdf outfile.pdf
""" % progname
sys.exit(1)
try:
argl = [ int(i) for i in sys.argv[1].split(" ") if i ]
infile = sys.argv[2]
outfile = sys.argv[3]
inpdf = pyPdf.PdfFileReader(file(infile,"rb"))
outpdf = pyPdf.PdfFileWriter()
for i in range(inpdf.numPages):
page = inpdf.getPage(i)
page.mediaBox.upperRight = tuple(argl[2:])
page.mediaBox.lowerLeft = tuple(argl[:2])
outpdf.addPage(page)
except:
usage(sys.argv[0])
(พอดีเปนงานดวน เลยเขียนแบบดวนจริง ๆ)
ขั้นตอนการแปลงคือ
ตัวเลข 4 ตัวคือคาเปนปอยต (pt) ของ x-มุมลางซาย y-มุมลางซาย และ x-มุมบนขวา y-มุมบนขวา ตามลําดับ หาได
โดยการ
64 of 65 10/17/2009 12:14 AM
Python Tutorial (เรียนรูไพธอน) http://debianclub.org/book/export/html/166
แถมอีกตัวอยางนึง
ทําขอบขาวรอบ pdf ขนาด A4 (595x842 ปอยต) โดยเวนระยะ 5 มม. (ประมาณ 14 ปอยต) โดยรอบ
$ ./croppdf.py "-14 -14 609 856" TEMPFILE.pdf OUTFILE.pdf
เสร็จแลวครับ
65 of 65 10/17/2009 12:14 AM