Tailieuhay 247compython Rat La Co Ban Vo Duy Tuan
Tailieuhay 247compython Rat La Co Ban Vo Duy Tuan
Tailieuhay 247compython Rat La Co Ban Vo Duy Tuan
Nhập môn lập trình Python cho phân tích (Trường Đại học Sư phạm Kỹ Thuật Thành
phố Hồ Chí Minh)
+MЪMXLMЖY
,MЖRRE]4]XLSRPɧQШXXVSRKRLоRKRKɺRRKоPϼTXVɳRL
чERKчвGGLɾʁFЮMXɴRLчEHϰRKZАиRKHдRKXLZMЖR
TLSRKTLɾZɧGШRKчТRKчɺRKчϲS
ɇɪPɧQZMЖGZЪM4,4RʆQZɧGɹRLоRKXɨGZдQɧ4,4
OLɹQɧXLрGLMЖRXРMYчвGOLMЎRQɳRLTLϲMXMЎTGϼRZЪM
4]XLSRXVSRKKMEMчSϰRRɧ]
'YРRWɨGLRLОRɧ]чвGZMЎXXVSRKUYɨXVɳRLQɳRLFϾXч϶Y
LМG4]XLSRZɧKMϲMUY]ЎXGɨGFɧMXSɨRGFϲRXLISRLYG϶Y
GжEQɳRL
,]ZМRKRLоRKKLMGLɰTGжEQɳRLGˢRKWЌKMɾTɴGLGLS
RLоRKEMчERKUYERXɩQчЎRZMЖGиRKHдRK4]XLSRZɧS
GɺRKZMЖGZɧ\мPʁLMЖRXϰM
1дGPдG
7ɨGLчвGGLMEPɧQGLRKQЦMGLRKWЌXVɳRLFɧ]
OLɴEGϰRLGжE4]XLSRQɧQɳRLWЌKІTTLϲMZɧWЌLоYɴGL
OLMFMЎXGɨGOMЎRXLиGRɧ]XVSRKZMЖGɨTHдRK4]XLSRZɧS
GɺRKZMЖGXVSRKXRKPEM
,IPPS[SVPH
'ɾTLɨT
4LɩRGLMEQSHYPI
'PEWW
8LESXɨGXVɱRXϼTXMR
<мPʁLɳRLϲRL
<мPʁJMPI.732
<мPʁJMPI<10
/ЎXRРM1]750
/ЎXRРM6IHMW
/ЎXRРM1IQGEGLIH
/ЎXRРM6EFFMX15
6IWXJYP'PMIRX
+ЮMIQEMPZЪM7184
7SGOIX4VSKVEQQMRK
8ɨGKMϲ
8ɱR:ɻ(Y]8YϴR
)QEMPXYERQEWXIV$KQEMPGSQ
*EGIFSSOLXXTW[[[JEGIFSSOGSQZSHY]XYER
'LRK,IPPS[SVPH
4]XLSRPɧQШXRKɺRRKоTLMɱRHКGL -RXIVTVIXIV0ERKYEKI
XиGPɧOLɺRKG϶RFYMPHXLɧRLJMPIXLрGXLMQɧGLϰ]XVрGXMЎT
RL4,4
,MЖRXϰM4]XLSRGɹRLɨRLGLɴRLPɧ\Zɧ\ЭRLɨRL\
чɪHкRKTLɨXXVMВRZɧчERKчиRKЮTLMɱRFϲR2LɨRL
4]XLSR\XLɳZϺRчERKчвGXMЎTXдGTLɨXXVMВR
;IFWMXIGLɴRLXLиGGжE4]XLSR[[[T]XLSRSVK
'ɧMчІX
4]XLSRLЦXVвL϶YLЎXGɨGRАRXϲRKZɧVϴXHДXɳQXLϴ]WЄR
XVɱRQШXWРLЖчMАYLɧRLRL1EG37ŷ
ɇВFMЎXPɧLЖXLРRKGжEFϰRчɪGɧM4]XLSRGLEGɹXLВZɧS
QɧRLɳRLGSQQERHPMRIZɧKɻ
$ python --version
2ЎYчɪGɧMчІXT]XLSRXLɳWЌLMВRXLКXLɺRKXMRTLMɱRFϲR
T]XLSR2ЎYFɨSPЦMXLɳчТRKRKLʨEZЪMFϰRGLEGɧMчІX
4]XLSR
'ɹXLВXLEQOLϲSGɨGLGɧMчІX4]XLSRXϰM
LXXTW[[[T]XLSRSVKHS[RPSEHW
'ɺRKGдTLɨXXVMВR
'LИG϶RHɽRKQШXXI\XIHMXSVPɧFϰRGɹXLВZMЎXчвGGSHI
T]XLSRLSІGGɹXLВHɽRKGɨGGɺRKGдGESGϴTLR -()
RL%TXERE4]'LEVQŷ'ɨG-()XLЬRKLЦXVвXLɱQUYɨ
XVɳRLTLɩRXɴGLGɾTLɨTHɸRKPЖRLHIFYKŷXVSRKTLϰQZM
GYРRWɨGLRLОRɧ]XLɳQɳRLLЪRKчЎRGɨGLXLрGXLM
T]XLSRFЀRKHɸRKPЖRL
,IPPS[SVPH
8ϰSQШXJMPIGɹXɱRPɧ helloworld.py ZɧGɹRШMHYRKRL
WEY
7EYчɹZɧSQɧRLɳRLGSQQERHPMRIHMGLY]ВRчЎRXL
QдGGLиEJMPIRɧ]ZɧKɻ
$ python helloworld.py
'LRK'ɾTLɨT
&MЎRWР
/LEMFɨSFMЎRFЀRKQШXGɩYPЖRLKɨR
a = 1
a = 1
a = 'Hello World'
a = [1, 2, 3]
a = [1.2, 'Hello', 'W', 2]
8SɨRXмWРLМG
4]XLSRGˢRKLЦXVвQШXWРXSɨRXмXSɨRLМGXLɺRKHдRK
RL
+ TLɰTGШRK
- TLɰTXVк
* TLɰTRLɩR
/ TLɰTGLME
% TLɰTGLMEPϴ]H QSHYPS
&SSPIERZɧ8SɨRXмPSKMG
+MɨXVКчɾRKZɧWEMXRKиRKPɧ True Zɧ False
not чВчϲSKMɨXVК
,ЦXVвHϰRKWSWɨRLOɰTRL
x = 2
8SɨRXмOMВQXVETL϶RXмXVSRKQШXXϼTLвT in OMВQXVE
GɹXТRXϰM not in OMВQOLɺRKXТRXϰM
'ϴYXVɾGчMАYOLMВR
4]XLSRLЦXVвQШXWРGϴYXVɾGчMАYOLMВRXLɺRKHдRK,϶Y
LЎXGɨGGϴYXVɾGчMАYOLMВRчАYHрEZɧSXLдXч϶YHɸRK
MRHIRXMSR чВXϰSXLɧRLQШXFPSGO\мPʁXLE]ZɳWмHдRK
{ ŷ } RLGɨGRKɺRRKоOLɨG 4,4.EZEWGVMTX
-JŷIPMJŷIPWI
if condition1 :
indentedStatementBlockForTrueCondition1
elif condition2 :
indentedStatementBlockForFirstTrueCondition2
elif condition3 :
indentedStatementBlockForFirstTrueCondition3
elif condition4 :
indentedStatementBlockForFirstTrueCondition4
else:
indentedStatementBlockForEachConditionFalse
7[MXGLŷGEWI
*SVŷMR
:ɴHд
/ЎXUYϲLMВRXLКGжEZɴHдXVɱR
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
;LMPI
while expression:
statement(s)
:ɴHд
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
/ЎXUYϲLMВRXLКGжEZɴHдXVɱR
,ɧQ
/LEMFɨSLɧQXLISGɾTLɨT
,ɧQRЎYOLɺRKXVϲHоPMЖYXLɳQІGчКRLWЌXVϲZАKMɨXVК
None
:ɴHдOLEMFɨSLɧQXɴRLZɧXVϲZАKMɨXVКXФRKGжEXLEQ
WРч϶YZɧS
'ɨGLKМMLɧQ
sum(1, 2)
(trả về giá trị là 3)
,ɧQGɹLЦXVвKMɨXVКQІGчКRLGLSXLEQWРOLMOLɺRK
XVY]АRZɧS:ɴHдLɧQWEY
2ЎYKМMLɧQXVɱRRLWEY
plus(2)
(kết quả trả về là 12)
1ШXOLɨGFMЖXXVSRKGɨGLKМMLɧQGжE4]XLSRWSZЪM4,4
PɧGLɾRKXEGɹXLВXLE]чФMXLиXрXLEQWРXVY]АRZɧSFЀRK
GɨGLчІXXɱRXLEQWРOLMKМMLɧQ:ɴHдXEGɹXLВKМMLɧQ
sum(a,b) ЮZɴHдXVɱRFЀRKGɨGLXVY]АRXLEQWР b XVЪG a
RLWEY
sum(b = 1, a = 10)
<мPʁGLYЦM
1ШXGLYЦMGɹXLВOLEMFɨSFЀRKHϴYRLɨ]чɺM " LSІGчR
' :ɴHдGɨGGLYЦMWEY
str1 = "Hello"
str2 = 'world'
'ɹXLВXVY]\YϴXXкRKOʁXрXVSRKQШXGLYЦMXLISLɳRLXLиG
MRHI\ZɴHд str1[0] str1[1] ŷ
'ɹXLВWмHдRKHϴYRLɨ] чɺMLSІGчR чВOLEMFɨS
GLYЦMXVɱRRLMАYHɸRK:ɴHд
2РMGLYЦM
'ɹXLВXϰSQШXGLYЦMHɧMXкZMЖGRРMGɨGGLYЦMPϰMXLISGɾ
TLɨT
8VɴGL\YϴXGLYЦMGSR
'ɹXLВXϰSGɨGGLYЦMGSRXLɺRKUYEXSɨRXмPϴ]OLSϲR
[start:end] VERKI 1ІGчКRL start PɧXкZКXVɴч϶YGLYЦM
0 Zɧ end PɧчЎRZКXVɴGYРMGLYЦM:ɴHд
print str[0:4]
(Hiển thị "Hell")
print str[:4]
(Hiển thị "Hell")
print str[-3:]
(Hiển thị "rld")
print str[6:-3]
(Hiển thị "wo")
0ϴ]чШHɧMGжEGLYЦM
8ɳQ XLE]XLЎRШMHYRK
'ɹXLВXɳQZɧXLE]XLЎXVSRKGLYЦMFЀRKGɨGLKМMTLRK
8ɳQZКXVɴGLYЦMGSR
'ɹXLВXɳQZКXVɴGжEQШXGLYЦMGSRXVSRKGLYЦMPЪRFЀRK
GɨGLKМMTLRKXLиG find(str, beg=0
end=len(string)) &ϾXч϶YPɧZКXVɴ 0 RЎYOLɺRKXɳQVEXLɳ
XVϲZА -1 :ɴHд
print str.find('Bye');
(hiển thị -1)
XиGPɧXкP϶R\YϴXLMЖRч϶YXMɱR'ɹXLВHɽRKLɧQ rfind()
чВXɳQXLISZКXVɴXкGYРMGLYЦMZАTLɴEXVЪG
8ɨGLGLYЦM
'ɹXLВXɨGLGLYЦMHрEXLISQШXGLYЦMHIPMQIXIVFЀRKGɨGL
KМMTLRKXLиG split(str="", num=string.count(str))
:ɴHд
8VMQOʁXрOLSЂRKXVϾRK
'ɹXLВPSϰMFОGɨGOʁXр QІGчКRLPɧOʁXрOLSϲRKXVϾRK
XVЪGZɧWEYQШXGLYЦMFЀRKGɨGLKМMGɨGTLRKXLиG
WEY
strip([chars]) PSϰMFОXVЪGZɧWEYGLYЦM
lstrip([chars]) PSϰMFОTLɴEXVЪGGLYЦM
rstrip([chars]) PSϰMFОTLɴEWEYGLYЦM
1ШXWРLɧQ\мPʁGLYЦM
isnumeric() /MВQXVEQШXGLYЦMGɹTLϲMPɧGLYЦMWР
lower() 'LY]ВRGLYЦMLЎXXLɧRLGLоXLЬRK
upper() 'LY]ВRGLYЦMLЎXXLɧRLGLо,3%
0MWX
0MWXXVSRK4]XLSRPɧGϴYXVɾGQϲRKZɧGɨGTL϶RXмGɹMRHI\
GɹXLиXр/LɺRKRL4,4OI]GжEQШXQϲRKGɹXLВZкE
PɧWРZкEPɧGLYЦM EWWSGMEXIHEVVE]
8VSRK4]XLSRQYРRXϰSQШXQϲRKGɹOI]PɧGLYЦMXLɳWЌ
WмHдRKGϴYXVɾG(MGXMSREV] TL϶RXMЎTXMЎT 8VSRKTL϶R
Rɧ]GLɾRKXEWЌRɹMчЎR0MWX1ШX0MWXчвGOLEMFɨSRL
QϲRKXVSRK.7327мHдRK [..] чВOLEMFɨSQШXQϲRK
:ɴHд
numbers = [1, 2, 3, 4, 5]
names = ['Marry', 'Peter']
'ɹXLВXVY]\YϴXXкRKTL϶RXмGжEQϲRKFЀRKMRHI\TL϶R
Xмч϶YXMɱRGɹXLиXрPɧ 0 :ɴHд
print numbers[0]
(Hiển thị 1)
print numbers[-3]
(Hiển thị 3)
print names[1]
(Hiển thị 'Peter')
ɇВFMЎXчвGWРPвRKTL϶RXмGжE0MWXGɹXLВWмHдRK
LɧQ len(array) чВPϴ]WРPвRKTL϶RXмGжEQϲRKXLEQ
WРXVY]АRZɧS
/MВQXVEWрXТRXϰMGжEQШXTL϶RXм
/MВQXVEXLIS-RHI\
8VSRKRLMАYXVЬRKLвTFϰRQYРRXVY]\YϴXQШXTL϶RXм
FϴXOΧ HрEZɧSMRHI\ GжEQϲRKXLɳRЎYXVY]\YϴXчЎRQШX
TL϶RXмOLɺRKXТRXϰMXLɳиRKHдRKWЌFɨSPЦM(SчɹXVЪG
OLMXVY]\YϴXQШXTL϶RXмFϰRG϶ROMВQXVE\IQTL϶RXм
Rɧ]чɪXТRXϰMLE]GLE,MЖRXϰMT]XLSROLɺRKLЦXVвLɧQ
RɧSчВOMВQXVEWрXТRXϰMGжEQШXTL϶RXмXVSRKQϲRK
'ɹGɨGLXLЬRKXLϴ]чВOMВQXVEчɹPɧŰ0SSOFIJSVI]SY
PIETű 0&=0 ZɧŰ)EWMIVXSEWOJSVKMZIRIWWXLER
TIVQMWWMSRű )%*4
:ɴHдZАŰ0SSOFIJSVI]SYPIET 0&=0 ű
:ɴHдZАŰ)EWMIVXSEWOJSVKMZIRIWWXLERTIVQMWWMSRű
)%*4
try:
array[index]
except IndexError:
# handle this
/MВQXVEXLISKMɨXVК
ɇВOMВQXVEQШXKMɨXVКGɹXТRXϰMOLɺRKXТRXϰMXVSRK
QϲRKLE]OLɺRKXLɳGɹXLВWмHдRKXSɨRXм in not in :ɴ
Hд
8VɴGL\YϴXQϲRKGSR
8RKXрRLGLYЦMXɹXLВXϰSGɨGQϲRKGSRXLɺRKUYE
XSɨRXмPϴ]OLSϲR [start:end] VERKI 1ІGчКRL start Pɧ
print numbers[:2]
(Hiển thị ['a', 'b'])
print numbers[-2:]
(Hiển thị ['c', 'd'])
<ɹETL϶RXмGжEQϲRK
numbers = [1, 2, 3, 4, 5]
del numbers[0]
print numbers
(Hiển thị [2, 3, 4, 5])
&ϰRGɹXLВ\ɹEQШXOLSϲRHрEZɧSXSɨRXмPϴ]OLSϲR
[start:end] :ɴHд
numbers = [1, 2, 3, 4, 5, 6, 7]
del numbers[2:4]
print numbers
(Hiển thị [1, 2, 5, 6, 7])
2РMQϲRK
&ϰRGɹXLВWмHдRKXSɨRXм + чВRРMKMɨXVКGжEQϲRKZɧ
XϰSVEQШXQϲRKPЪRGɹWРPвRKTL϶RXмPɧXФRKWРPвRK
TL϶RXмGжEQϲRKGSR:ɴHд
a = [1, 2]
b = [1, 3]
print a + b
(Hiển thị [1, 2, 1, 3])
8LɱQTL϶RXмZɧSQϲRK
2ЎYFϰRQYРRXLɱQTL϶RXмZɧSQШXQϲRKчɪXТRXϰMLɪ]
HɽRKTLRKXLиG list.append(newvalue) чВXLɱQTL϶R
XмGɹKMɨXVК newvalue ZɧSGYРMQϲRK list :ɴHд
numbers = [1, 2, 3]
numbers.append(4)
print numbers
(Hiển thị [1, 2, 3, 4]
0ϴ]TL϶RXмGYРMQϲRK
2ЎYQYРRPϴ]TL϶RXмGYРMGɽRKGжEQϲRKVEOLОMQϲRK
GɹXLВWмHдRKTLRKXLиG list.pop() WЌXVϲZАKMɨXVК
GжETL϶RXмGYРMGɽRKZɧQϲRKFɩ]KMЬWЌOLɺRKGɸRTL϶R
XмRɧ]
numbers = [1, 2, 3]
mynumber = numbers.pop()
print mynumber
(Hiển thị 3)
print numbers
(Hiển thị [1, 2])
8ɳQQШXKMɨXVКXVSRKQϲRK
/LMGLϰ]WЌLMВRXLКOЎXUYϲ
ɇϲSRKвGKMɨXVКGжEQϲRK
ɇВчϲSRKвGXLиXрGɨGKMɨXVКGжEQШXQϲRKWмHдRK
TLRKXLиG list.reverse() 4LRKXLиGRɧ]OLɺRKXVϲ
ZАOЎXUYϲQɧXLE]чФMXVрGXMЎTQϲRK list :ɴHд
numbers = [1, 2, 3, 4]
numbers.reverse()
print numbers
(Hiển thị [4, 3, 2, 1])
7ϾT\ЎTKMɨXVКGɨGTL϶RXм
ɇВWϾT\ЎTXLиXрGжEKMɨXVКXVSRKQϲRKWмHдRKTLRK
XLиG list.sort([func]) чВWϾT\ЎT2ЎYXLEQWРч϶Y
ZɧSPɧLɧQ func OLɺRKXVY]АRZɧSXLɳQІGчКRLPɧWϾT\ЎT
XLISKMɨXVКXʆRKH϶R4LRKXLиGRɧ]OLɺRKXVϲZАOЎX
UYϲQɧXLE]чФMXVрGXMЎTQϲRK list :ɴHд
8YTPI
8YTPIGˢRKPɧQШXGϴYXVɾGQϲRKXRKXрRLGϴYXVɾG
0MWX1ШXWРчMВQOLɨGRLEYGFϲRPɧOLEMFɨS8YTPIWм
HдRKGІTHϴYRKSІG (...) ZɧQШXXYTPIчɪчвGOLEMFɨS
VТMXLɳOLɺRKXLE]чФMчвGKMɨXVК MQQYXEFPI ZɧOLɺRKLЦ
XVвGɨGTLRKXLиGRL append() pop() ŷ:ɴHд
:ϺRLЦXVвGɨGGɨGLчВXVY]\YϴXTL϶RXмKMРRK0MWXRLPɧ
XVY]\YϴXXLISMRHI\VERKIXɳQOMЎQŷ
(MGXMSREV]
(MGXMSREV]GˢRKPɧQШXGϴYXVɾGQϲRKRLRKGɨGTL϶RXм
FESKТQOI]ZɧZEPYI2ЎYFϰRGɹFMЎX.732XLɳGϴYXVɾG
(MGXMSREV]XRKXрRLQШXSFNIGXNWSR1ШX(MGXMSREV]
чвGOLEMFɨSFЀRKGІTHϴYRKSІG {...} :ɴHд
8VY]\YϴXQШXKMɨXVКHрEZɧSOI]GжEчРMXвRK:ɴHд
8LɱQQШXTL϶RXм
ɇВXLɱQQШXTL϶RXмZɧSчРMXвRKчɪOLEMFɨSWмHдRK
GϴYXVɾG dict[key] = value :ɴHд
1ШXWРLɧQTLRKXLиGXLɺRKHдRK
dict.clear() <ɹEXSɧRFШHоPMЖYFɱRXVSRKчРM
XвRK
dict.copy() 8VϲZАQШXFϲRGST]GжEчРMXвRK
чРMXвRKLE]OLɺRK
dict.keys() 8VϲZАQШX0MWXGLиEGɨGOI]
dict.values() 8VϲZАQШX0MWXGLиEGɨGZEPYI
'LRK4LɩRGLMEQSHYPI
8ϴXGϲZɴHдGLSчЎRXLЬMчMВQRɧ]чАYчвGXLрGXLMXVSRK
GSQQERHPMRILSІGXкQШXJMPIT]XLSR .py 8Y]RLMɱRчРM
ZЪMGɨGиRKHдRKPЪRGɹRLMАYGLиGRʆRKXLɳTLɩRGLMERLО
HрɨRXLɧRLGɨGJMPIOLɨGRLEYWЌKMɾTHДFϲSXVɳZɧXɨMWм
HдRKGɨGXLɧRLTL϶RчɪXLMЎXOЎ
'LRKRɧ]WЌKMɾTFϰRXLMЎXOЎGɨGXɴRLRʆRKXLISQɺ
LɳRLGɨGQSHYPIZɧOLMG϶RXLɳWЌKМMJMPIXRKиRKZɧWм
HдRK
'ɨGPSϰMQSHYPIXLZMЖR
'ɹPSϰMQSHYPIXLЬRKXLϴ]Pɧ
'1SHYPIPMɱROЎXZЪMXVɳRLTLMɱRHКGL
ɇЬRKHϺRXɳQчВPSEHQSHYPI
ɇВXϲMQШXQSHYPIZɧSWGVMTXGжEFϰRWмHдRKGɾTLɨT
чRKMϲR
import modulename
OLMKІTGɩYPЖRLXVɱRXLɳXVɳRLFMɱRHКGLWЌXMЎRLɧRLXɳQ
OMЎQJMPIQSHYPIXRKиRKXLISXLиXрXLQдGWEY
8LQдGLMЖRLɧRLQɧWGVMTXчERKKМM
'ɨGXLQдGXVSRK4=8,324%8, RЎYGɹWIX
'ɨGXLQдGGɧMчІXGLYϸRXVɱR0MRY\9RM\
'ɹXLВFMЎXчвGчЬRKHϺRQɧQШXQSHYPIчɪчвGPSEH
FЀRKчSϰRGSHIHЪMчɩ]
import math
math.__file__
(Ví dụ trả về '/usr/lib/python2.5/lib-dynload/math.
so')
import random
random.__file__
(Ví dụ trả về '/usr/lib/python2.5/random.pyc')
0ϴ]HERLWɨGLXLYШGXɴRLZɧTLRK
XLиGGжEQШXQSHYPI
ɇВPϴ]чвGHERLWɨGLGɨGXLYШGXɴRLZɧTLRKXLиGQɧ
QSHYPILЦXVвWмHдRKLɧQ dir(modulename) :ɴHд
dir(math)
['__doc__', '__file__', '__name__', '__package__',
'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',
'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degree
s', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'fa
ctorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma'
, 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'lo
g', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians
', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
'ɨGLOLEMFɨSZɧWмHдRKQSHYPI
+MϲWмFϰRXϰSQШXJMPIT]XLSR mymath.py GɹRШMHYRKRL
WEY
import mymath
num1 = 1
num2 = 2
:ɧSGSQQERHPMRIXLрGLMЖRKМMJMPIQ]I\EQTPIRLWEY
$ python myexample.py
7EYOLMXLрGLMЖRWЌLMВRXLКPɱRQɧRLɳRLPɧ
4EGOEKIQSHYPI
'ɹXLВKSQRLMАYQSHYPI .py ZɧSQШXXLQдGZɧXɱRXL
QдGPɧXɱRGжETEGOEKIZɧXϰSQШXJMPI __init__.py XVSRK
XLQдGRɧ]
2LZϼ]GϴYXVɾGXLGжEQШXTEGOEKIWЌRLWEY
|-- mypack
| |-- __init__.py
| |-- mymodule1.py
| |-- mymodule2.py
|
import mypack.mymodule1
LSІG
LSІG
/LMWмHдRKQШXQSHYPIXLYШGQШXTEGOEKIXLɳGɨGPЖRL
XVSRKJMPI __init__.py WЌчвGXLрGLMЖRXVЪG8LɺRK
XLЬRKXLɳJMPI __init__.py WЌVЦRK
'ɹXLВXϰSGɨGWYFTEGOEKIFɱRXVSRKQШXTEGOEKIXLIS
чɾRKGϴYXVɾGXLQдGGɹJMPI __init__.py :ɴHд
import mypack.mysubpack.mysubsubpack.module
'LRK'PEWW
0ϼTXVɳRLLЪRKчРMXвRKPɧQШXOLɨMRMЖQOLɺRKXLВ
XLMЎYXVSRKL϶YLЎXGɨGRKɺRRKоXLɺRKHдRKLMЖRRE]
4]XLSRGˢRKLЦXVвPϼTXVɳRLLЪRKчРMXвRKZЪMGɨGOLɨM
RMЖQ'PEWW3FNIGX3ZIVVMHIŷ
/LEMFɨSQШX'PEWW
/LEMFɨSQШXGPEWWXLISGɾTLɨTWEY
class myclass([parentclass]):
assignments
def __init__(self):
statements
def method():
statements
def method2():
statements
:ɴHдQШXGPEWW
class animal():
name = ''
name = ''
age = 0
def __init__(self, name = '', age = 0):
self.name = name
self.age = age
def show(self):
print 'My name is ', self.name
def run(self):
print 'Animal is running...'
def go(self):
print 'Animal is going...'
class dog(animal):
def run(self):
print 'Dog is running...'
myanimal = animal()
myanimal.show()
myanimal.run()
myanimal.go()
mydog = dog('Lucy')
mydog.show()
mydog.run()
mydog.go()
7EYOLMXLрGXLMWЌGLSVEOЎXUYϲ
My Name is
Animal is running...
Animal is going...
My Name is Lucy
Dog is running...
Animal is going...
8VSRKZɴHдXVɱRXLɳ
XLиGXLɳOLɺRKG϶RXVY]АRXLEQWРRɧ]
4LRKXLиG run() GжEGPEWW dog KМMPɧ override
GжETLRKXLиG run() GжEGPEWW animal
'LRK8LESXɨGXVɱRXϼTXMR
Zɧ8LQдG
2ШMHYRKGLRKRɧ]WЌLЪRKHϺRGɨGXLESXɨGPMɱRUYER
чЎRXϼTXMRZɧXLQдG
8ϼTXMR *MPI
1ЮJMPI
8VЪGOLMQYРRчМGLSІGKLMJMPIFϰRG϶RGɹXLESXɨGQЮ
JMPIXLISGɾTLɨT
fh = open(filepath, mode)
r QЮчВчМGRШMHYRK QІGчКRL
w QЮчВKLMRШMHYRK
a QЮчВKLMXLɱQRШMHYRKZɧSGYРMJMPI
r+ QЮчВчМGZɧKLM'SRXVОRЀQЮч϶YJMPI
w+ QЮчВчМGZɧKLM+LMчɯRЎYJMPIчɪXТRXϰMRЎY
JMPIGLEXТRXϰMXLɳXϰSJMPIQЪMчВKLM
a+ QЮчВчМGZɧXLɱQZɧSGYРMJMPI'SRXVОRЀQЮ
GYРMJMPI2ЎYJMPIGLEXТRXϰMXLɳXϰSJMPIQЪMчВKLM
1ІGчКRLPɧQЮJMPIXI\XRЎYQYРRQЮJMPIRLКTLɩR
FMREV] XLɳXLɱQ b ZɴHд rb wb ab rb+ wb+ ab+
:ɴHд
f1 = open('test.txt', 'r')
f2 = open('access_log', 'a+'
closed 8VYIRЎYJMPIчɪчɹRK
mode GLЎчШOLMQЮJMPI
name XɱRGжEJMPI
softspace GЬчɨRLHϴYWSJXWTEGIOLMHɽRKZЪMLɧQ
ɇМGRШMHYRKXкJMPI
7EYOLMJMPIчɪQЮЮGLЎчШчМGXLɳKМMTLRKXLиG
read([count]) чВXVϲZАXSɧRFШRШMHYRKGжEJMPI:ɴHд
f1 = open('test.txt', 'r')
data = f1.read();
f2 = open('log.txt', 'r')
buffdata = f2.read(1024)
+LMRШMHYRKZɧSJMPI
2ЎYJMPIчвGQЮЮGLЎчШGɹXLВKLMXLɳGɹXLВHɽRK
TLRKXLиG write() чВKLMQШXRШMHYRKZɧSJMPI:ɴHд
f2 = open('access_log', 'a+')
f2.write('Attack detected')
ɇɹRKJMPIчɪQЮ
7EYOLMLSɧRXϴXGɨGXLESXɨGчМGKLMJMPIXLɳKМMTLRK
XLиG close() чВчɹRKJMPIчɪQЮ:ɴHд
f1.close()
f2.close()
ɇФMXɱRJMPI
import os
os.rename('test.txt', 'test_new.txt')
<ɹEJMPI
OLОMLЖXLРRK:ɴHд
import os
os.remove('test.txt')
8LQдG (MVIGXSV]
8ϰSXLQдG
import os
os.mkdir('test')
<ɹEXLQдG
import os
os.rmdir('test')
ɇМGRШMHYRKXLQдG
import os
allfiles = os.listdir('/root/downloads')
print allfiles
1SHYPI os
1SHYPI os PɧQШXQSHYPIGɹRLMАYTLRKXLиGLоYɴGL
XVSRKZMЖGPɧQZMЖGZЪMGɨGJMPIZɧHMVIGXSV]RL
os.chdir(path) чФMXLQдGLMЖRLɧRL
os.getcwd() XVϲZАXLQдGLMЖRLɧRL
os.removedirs(path) \ɹEQШXчЬRKHϺR Gɹ
VIGYVWMZI
<IQXLɱQXϰMLXXTWHSGWT]XLSRSVKPMFVEV]SWLXQP
1SHYPI os.path
1SHYPI os.path LЦXVвGɨGTLRKXLиGKMɾTXLESXɨG
RLERLGLɹRKZɧXLYϼRXMЖRLRXVɱRчЬRKHϺR
os.path.exists(path) OMВQXVEчЬRKHϺRGɹXТR
XϰMLE]OLɺRK
os.path.getsize(path) Pϴ]JMPIWM^I F]XI
os.path.isfile(path) OMВQXVE\IQGɹTLϲMPɧQШX
JMPIXLɺRKXLЬRK
os.path.isdir(path) OMВQXVE\IQGɹTLϲMPɧQШX
XLQдG
os.path.dirname(path) XVϲZАXɱRXLQдGGжETEXL
os.path.getatime(path) XVϲZАXLЬMKMERXVY]GϼT
QЪMRLϴX
os.path.getmtime(path) XVϲZАXLЬMKMERGLИRLWмE
GYРMGɽRK
os.path.getctime(path) XVϲZАXLЬMKMERGLИRLWмE
GYРMGжEQIXEHEXEXVɱRQШXWРLЖXLРRK,SІGXVϲZА
XLЬMKMERXϰSJMPIXVɱR;MRHS[W
<IQXLɱQXϰM
LXXTWHSGWT]XLSRSVKPMFVEV]SWTEXLLXQP
'LRK<мPʁLɳRLϲRL
7мHдRKXLZMЖR4MPPS[ 4-0*SVO чВXMЎRLɧRLGɨGXLES
XɨG\мPʁLɳRLϲRLчRKMϲRRLVIWM^IGVSTVSXEXIŷ
'ɧMчІX4-0
:ɧSXVERK[IFWEYчВHS[RPSEHGɧMчІXTEGOEKI4-0GLS
T]XLSRGжEFϰR
LXXTTMPPS[VIEHXLIHSGWSVKIRPEXIWXMRWXEPPEXMSRLXQP
7EYOLMGɧMчІXXLɳGɹXLВWмHдRKGɨGQSHYPIXVSRK
TEGOEKI-40
1ЮJMPI
from PIL import Image
im = Image.open("photo.jpg")
7EYOLMQЮJMPILɳRLXLɧRLGɺRKXLɳGɹXLВXLESXɨGXVɱRчРM
XвRK im
+LMJMPI
8кчРMXвRK Image GɹXLВPYJMPI\YРRKQɨ]XɴRLFЀRK
TLRKXLиG save(path, type) :ɴHд
...
im.save('photo_new.jpg', 'JPEG')
8ϰSXLYQFREMP
7мHдRKTLRKXLиG thumbnail RLWEY
thumbnail OLɺRKXVϲZАMQEKIQЪMQɧXLрGLMЖRXVɱR
SFNIGXMQEKIчERKKМM
'ɨGXLESXɨG\мPʁLɳRLϲRL
8LEQOLϲSXLɱQXLZMЖR4-0XϰM
LXXTTMPPS[VIEHXLIHSGWSVKIRPEXIWXMRHI\LXQP
'LRK<мPʁJMPI.732
.732PɧQШXXVSRKRLоRKчКRLHϰRKJMPIXVESчФMHоPMЖY
XLɺRKHдRKRLϴXLMЖRRE]:ЪMOMЎRXVɾGчRKMϲRZɧXRK
чТRKZЪMGϴYXVɾGGжE4]XLSRRɱRZMЖGXLESXɨG.732XVɱR
4]XLSRVϴXHДLMВY
0SEHJMPIXк-RXIVRIX
8LɺRKXLЬRKHоPMЖY.732чвGPϴ]XкRKYТROLɨG RL
JMPIMRXIVRIX RɱRGLRKRɧ]WЌFϾXч϶YFЀRKGɨGL
LЪRKHϺRHS[RPSEHQШXJMPI.732Xк-RXIVRIXZɧWEYчɹ
QЪMTEVWMRKRШMHYRK.732HS[RPSEH
import urllib2
import json
response = urllib2.urlopen('https://api.github.com/
users/voduytuan/repos')
data = json.load(response)
print data
:ɴHдXVɱRWЌXVY]ZϴRчЬRKHϺR
LXXTWETMKMXLYFGSQYWIVWZSHY]XYERVITSWчВPϴ]HERL
WɨGL6ITSWMXSV]XVɱR+MXLYFGжEQɳRLHЪMчКRLHϰRK
.7327EYчɹWЌчвG
4EVWMRK.732(EXE
2ЎYRLFϰRчɪGɹ.732HEXEHЪMHϰRKGLYЦMQYРR
TEVWMRKGLYЦMRɧ]XLɧRL(EXEXLɳWмHдRKRLGɨGLHЪM
чɩ]
import json
mystring = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
data = json.loads(mystring)
print data
(Hiển thị: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd
': 4})
)RGSHMRK.732(EXE
2ЎYRLFϰRчɪGɹQШXFMЎRZɧQYРRIRGSHIXLɧRL.732
WXVMRKXLɳGɹXLВHɽRKXLISGɨGLWEY
import json
mydata = {
'name': 'John',
'age': 10
}
jsonstring = json.dumps(mydata)
print jsonstring
(hiển thị: {"age": 10, "name": "John"})
'LRK<мPʁJMPI<10
8VSRKTL϶RRɧ]GLɾRKXEWЌTEVWMRKRШMHYRK<10XLɧRL
HоPMЖYчВ\мPʁɇВ\мPʁ<10XEWЌWмHдRKXLZMЖR
&IEYXMJYPWSYTɇɩ]PɧQШXXLZMЖRKMɾTZMЖGXVMВROLEM
ZMЖGTEVWMRKLXQP\QPчвGRLERLGLɹRKZɧXMЖRPвM
'ɧMчІX&IEYXMJYPWSYT
&ϰRGɹXLВXLEQOLϲSLЪRKHϺRGɨGLGɧMчІXXϰM[IFWMXI
LXXT[[[GVYQQ]GSQWSJX[EVI&IEYXMJYP7SYTFWHSGMRW
FIEYXMJYPWSYT
LXXT[[[GVYQQ]GSQWSJX[EVI&IEYXMJYP7SYTFWHSGMRW
ETEVWIV
:ɴHдZАTEVWMRK<10
'LSZɴHдWEY
note = '''
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waff
les with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
foods = soup.findAll('food')
for x in foods:
print x.find('name').string, ': ', x.price.stri
ng
/LMGLϰ]XLɳWЌLMВRXLКVEQɧRLɳRLRLWEY
8VSRKZɴHдGɹQШXWРGɨGLXVY]\YϴXчЎRGɨGTL϶RXмRL
findAll() XVϲZАQϲRKGɨGXLЊGɹXɱRG϶RXɳQ
find() XVϲZАTL϶RXмч϶YXMɱRGɹXɱRG϶RXɳQ
8VY]\YϴXXVрGXMЎTXLɺRKUYEXɱRXLЊRL
x.price.string
4EVWMRK,810
8RKXрRL xml &IEYXMJYP7SYTGɹXLВTEVWMRKRШMHYRK
,810XLɺRKUYELɧQOLЮMXϰSZɧGLМR html ЮXLEQWР
XLи
...
soup = Soup(websitehtml, 'html')
'LRK/ЎXRРM1]750
1]750PɧQШXLЖGWЮHоPMЖYUYERLЖTLФFMЎRRLϴXLMЖR
RE]6ϴXRLMАYRKɺRRKоGɹXLВOЎXRРMчЎR1]750Zɧ
4]XLSRGˢRKOLɺRKRKSϰMPЖ
1ІGчКRL4]XLSROLɺRKGɹXLZMЖRчВOЎXRРMчЎR1]750
WIVZIV8VSRKTL϶RRɧ]чВOЎXRРMчЎR1]7507IVZIVXк
4]XLSRGLɾRKXEWЌWмHдRKQSHYPI MySQLdb
'ɧMчІX1]750HF
'ɧMчІXXLɺRKUYE pip RLWEY
8LEQOLϲSXLɱQXϰMLXXTWT]TMT]XLSRSVKT]TM1]750
T]XLSR
/LEMFɨSQSHYPI1]750HFPɧGɹXLВWмHдRK
import MySQLdb
8VSRKQШXWРXVЬRKLвTчɪGɧM1]750HFRLRKMQTSVX
FɨSPЦMXLMЎYJMPI libmysqlclient.18.dylib 2KY]ɱRRLɩR
GɹXLВPɧHSLMЖRXϰMчЬRKHϺRчЎRJMPIOLɺRKXТRXϰM8Lм
XϰSW]QPMROLSІGWмHдRKGɩYPЖRLWEYчВXϰSW]QPMROXк
JMPI libmysqlclient.18.dylib чЎRXLQдG /usr/lib/
$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18
.dylib /usr/lib/libmysqlclient.18.dylib
/ЎXRРMчЎR1]7507IVZIV
&ϰRG϶RGɹQШX1]750WIVZIVчERKGLϰ]ZɧGLSOЎXRРM
чЎR8VSRKXVЬRKLвTRɧ]PɧPSGEPLSWXRɱROLɺRKG϶RGϴY
LɳRLчІGFMЖXGLИG϶RGYRKGϴTYWIVREQIZɧTEWW[SVHPɧ
GɹXLВOЎXRРMчЎR1]7507IVZIV
8LрGLMЖRKМMLɧQRLWEYчВXVϲZАOЎXRРM
import MySQLdb
2ЎYOЎXRРMOLɺRKXLɧRLGɺRKXLɳWЌFɨSPЦMZɧRKRK
GLRKXVɳRL'ɨGLOЎXRРMERXSɧRPɧчEZɧSXVSRK try
чВFϾXPЦMRLWEY
import MySQLdb
db = None
try:
db = MySQLdb.connect(host = 'localhost', user =
'root', passwd = 'root', db = 'mysql')
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
if db:
cur = db.cursor()
cur.execute("SELECT VERSION()")
ver = cur.fetchone()
print "Database version : %s " % ver
...
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'test', charset = 'utf8'
)
5YIV]HоPMЖY
ɇВXVY]ZϴRHоPMЖY GLϰ]GɩYPЖRL750 XLɳWмHдRK cursor
GжE1]750HF:ɴHд
import MySQLdb
import MySQLdb
*IXGLHоPMЖY
'ɹQШXWРGɨGLчВJIXGLHоPMЖYXLɺRKHдRKXк cursor WEY
OLMчɪ exectute(sql) Pɧ fetchone() Zɧ fetchall()
fetchone() GLИJIXGLQШXHɸRKHоPMЖY2ЎYQYРR
JIXGLRLMАYHɸRKHоPMЖYXLɳGɹXLВKМMRLMАYP϶RQЦM
P϶RWЌXVϲZАQШXHɸRKHоPMЖY8РXGLSXVЬRKLвTXVY]
ZϴRVϴXRLMАYHоPMЖYQШXPɾG2ЎYXVϲZА None XиGPɧ
чɪJIXGLLЎXHоPMЖYXкGɩYXVY]ZϴR
fetchall() JIXGLXSɧRFШHоPMЖYXVY]ZϴRчвGXк
GɩYXVY]ZϴRZɧXVϲZАQШXXYTPIGLиEGɨGHɸRKHо
PMЖY1ЦMTL϶RXмGжE8YTPIGɹXLВPɧQШX8YTPIOLɨG
LSІGPɧQШX(MGXMSREV]Xɽ]XLISGɧMчІXЮFЪGPϴ]
GYVWSV <IQTL϶R
fetchmany(size) RЀQЮKMоEOMВYJIXGLXVɱRGɹXLВ
UY]чКRLWРPвRKVS[XVSRKQЦMP϶RJIXGL2ЎYJIXGL
LЎXXLɳXVϲZА8YTPIVЦRK
ɇɹRKOЎXRРM
7EYOLMOЎXRРMZɧXVY]ZϴRXLɳGɹXLВчɹRKOЎXRРMXLISZɴ
HдWEY
import MySQLdb
db = MySQLdb.connect(...)
db.close()
import MySQLdb
db = MySQLdb.connect(...)
cursor = db.cursor()
cursor.close()
db.close()
4VITEVIH7XEXIQIRX
4VITEVIHWXEXIQIRXPɧOцXLYϼXXLEQWРLɹEGɨGHоPMЖY
XVY]АRZɧSGɩYXVY]ZϴRXLE]ZɳRРMGLYЦMXVрGXMЎTчВ\ɩ]
HрRKQШXGLYЦMXVY]ZϴRHɧM/цXLYϼXRɧ]чвGɨTHдRK
RLMАYZɧKMɾTXʆRKLMЖYUYϲZɧXɴRLFϲSQϼXGжEGɩYXVY]
ZϴR:ɴHд
...
cur.execute("UPDATE Writers SET Name = %s WHERE Id
= %s", ("John", "4"))
...
1ЦMXLEQWРXVY]ZϴRWЌчвGXLE]XLЎFЀRK %s ZɧTLRK
XLиG execute() WЌGɹXLEQWРXLиPɧQШX8YTPIGɹKMɨXVК
XRKиRKZЪMXLиXр\YϴXLMЖRGжEGɨGXLɧRLTL϶R %s
'LRK/ЎXRРM6IHMW
6IHMWPɧQШXQIQSV]GEGLIWIVZIVLЦXVвTIVWMWXERXHEXE
XLɺRKHдRKRLϴXLMЖRRE]2ШMHYRKGLRKRɧ]WЌLЪRK
HϺRFϰROЎXRРMчЎRQШX6IHMWWIVZIV чɪчвGGɧMчІX
WЄR XLɺRKUYEXLZMЖRVIHMWT]
'ɧMчІX
'ɹXLВ\IQXLɱQZАLЪRKHϺRGɧMчІXXLZMЖRRɧ]XϰM
LXXTWKMXLYFGSQERH]QGGYVH]VIHMWT]
/ЎXRРMчЎR6IHMW
ɇВOЎXRРMчЎR6IHMWWIVZIVXLɳFϰRGɹXLВ\IQZɴHдWEY
import redis
r = redis.StrictRedis(host='localhost', port=6379,
db=0)
8LрGLMЖRPЖRL
8LрGLMЖRGɨGPЖRLFɳRLXLЬRKXVɱRчРMXвRKVIHMW:ɴHд
import redis
r = redis.StrictRedis(...)
r.set('foo', 'bar')
print r.get('foo')
(Hiển thị 'bar')
4MTIPMRI
4MTIPMRIPɧOцXLYϼXчвGHɽRKXVSRKXVЬRKLвTFϰRQYРR
XʆRKTIVJSVQERGIFЮMKШTRLMАYPЖRLZɧSQШXVIUYIWXXLE]
ZɳQЦMPЖRLPɧQШXVIUYIWXRLXLɺRKXLЬRK<IQZɴHд
WEYчВLMВYGɨGLWмHдRKTMTIPMRIFЀRK redis-py
import redis
r = redis.StrictRedis(...)
r.set('foo', 'bar')
pipe = r.pipeline()
pipe.set('a', 1)
pipe.set('b', 2)
pipe.set('c', 3)
pipe.get('foo')
pipe.execute()
'LRK/ЎXRРM
1IQGEGLIH
1IQGEGLIHPɧQШXQIQSV]GEGLIWIVZIVXLɺRKHдRKLMЖR
RE]2ШMHYRKGLRKRɧ]WЌLЪRKHϺRFϰROЎXRРMчЎR
QШX1IQGEGLIHWIVZIV чɪчвGGɧMчІXWЄR XLɺRKUYE
XLZMЖR pylibmc
'ɧMчІX
'ɹXLВ\IQXLɱQZАLЪRKHϺRGɧMчІXXLZMЖRRɧ]XϰM
LXXTWIRHETEXGLWITVSNIGXWT]PMFQGMRWXEPPLXQP
/ЎXRРMчЎR1IQGEGLIH7IVZIV
ɇВOЎXRРMчЎR1IQGEGLIHWIVZIVXLɳFϰRGɹXLВ\IQZɴHд
WEY
import pylibmc
8LрGLMЖRPЖRL
8LрGLMЖRGɨGPЖRLFɳRLXLЬRKXVɱRчРMXвRKQIQGEGLI
:ɴHд
import pylibmc
mc = pylibmc.Client(...)
mc.set('foo', 'bar')
print mc.get('foo')
(Hiển thị 'bar')
'LRK/ЎXRРM6EFFMX15
6EFFMX15PɧQШXTL϶RQАQGLSTLɰT\ɩ]HрRK1IWWEKI
5YIYIXLISTVSXSGSP%154ZɧOLɨXLɺRKHдRKXVɱRXLЎ
KMЪMɇВOЎXRРMчЎR6EFFMX15XVɱR4]XLSRXEWЌWмHдRK
XLZMЖR pika
'ɧMчІX
'ɹXLВ\IQXLɱQZАLЪRKHϺRGɧMчІXXLZMЖRRɧ]XϰM
LXXTWTMOEVIEHXLIHSGWSVKIR
+ЮMQШXQIWWEKIчЎR7IVZIV
4VSZMHIV
:ɴHдчВKЮMQШXQIWWEKIчЎRWIVZIV
import pika
connection = pika.BlockingConnection(pika.Connectio
nParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='', routing_key='hel
lo', body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
ɇВKЮMQШXQIWWEKIGLɾRKXEG϶ROЎXRРMчЎRWIVZIVZɧ
OLEMFɨSQШXGLERRIPЮчɩ]PɧGLERRIPGɹXɱRPɧ hello
7EYOLMOLEMFɨSGLERRIPXESXMЎRLɧRLKЮMQIWWEKIGɹ
RШMHYRK Hello World! XLɺRKUYEGLERRIPRɧ]OɯQXLIS
OLEMFɨS routing_key Pɧ hello 6SYXMRK/I]WЌKMɾTчMАY
LЪRKQIWWEKIRɧ]чЎRчɾRKGɨG[SVOIVчвGOLEMFɨS
RLϼRQIWWEKIXLISVSYXMRKOI] 'SRWYQIV
2LϼRQIWWEKI'SRWYQIV
ЭFЪGXVЪGXEчɪXϰSQШXQIWWEKIPɱRUYIYIЭFЪG
Rɧ]XEWЌOLEMFɨSQШX[SVOIV\мPʁGɨGQIWWEKIRLϼR
чвGXкGLERRIP hello
import pika
connection = pika.BlockingConnection(pika.Connectio
nParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.start_consuming()
ɇSϰRGSHIRɧ]GˢRKGɹTL϶ROLEMFɨS connection
channel 8Y]RLMɱRZɳPɧGSRWYQIVRɱRWЌWмHдRK
TLRKXLиG basic_consume чВPϾRKRKLIXVɱRUYIYI
hello OLMGɹQIWWEKIчЎRWЌKМMLɧQ callback() чВ\м
Pʁ8VSRKXVЬRKLвTZɴHдRɧ]XLɳGEPPFEGOGLИчRKMϲRPɧ
LMВRXLКGLYЦMXLɺRKFɨSчɪRLϼRчвGQIWWEKI
8ɳQLMВYXLɱQZА6EFFMX15Zɧ4MOE
2ШMHYRKGLRKRɧ]OLɺRKGɹʁчКRLKMЪMXLMЖYXϴXGϲOLɨM
RMЖQGжE%154GˢRKRL6EFFMX15QɧGLж]ЎYKMЪMXLMЖY
XLZMЖR pika чВPɧQZMЖGZЪM6EFFMX15&ϰRGɹXLВXMЎT
XдGXLISHɻMGɨGLЪRKHϺRZАOLɨMRMЖQGжE6EFFMX15Zɧ
4MOEXϰM[IFWMXIGLɴRLXLиGGжE6EFFMX15
LXXTW[[[VEFFMXQUGSQXYXSVMEPWXYXSVMEPSRI
T]XLSRLXQP
'LRK6IWXJYPGPMIRX
2Kɧ]RE]ZЪMWрTLSRKTLɾGжEGɨGиRKHдRKZɧRLYG϶Y
OЎXRРMRKɧ]GɧRKPЪRXLɳ6IWXJYPPɧQШXXVSRKRLоRKQɺ
LɳRL[IFWIVZMGIчвGRLMАYGɺRKX]WмHдRK(SчɹZMЖG
GɹXLВOЎXRРMчЎRGɨG6IWXJYP[IFWIVZMGIPɧQШXOцRʆRK
G϶RXLMЎXGLSGɨGPϼTXVɳRLZMɱR
'LRKRɧ]WЌKMЪMXLMЖYZАQШXXVSRKRLоRKXLZMЖRRФM
XMЎRKRLϴXXVSRK4]XLSRчВPɧQZMЖGZЪMGɨG6IWXJYP[IF
WIVZMGIчɹPɧ requests
;IFWMXIGLɴRLXLиGZɧGɨGQɺXϲч϶]чжчАYчвGчАGϼT
XϰMLXXT[[[T]XLSRVIUYIWXWSVK
'ɧMчІX
'ɧMчІXRLERLGLɹRKXLɺRKUYE pip RLWEY
6IUYIWX
,ЦXVвWЄRGɨGTLRKXLиGXRKиRKGLS,XXTVIUYIWX
RL+)84378498()0)8)ŷ
import requests
r = requests.get('https://api.github.com/events')
r = requests.post("http://httpbin.org/post")
r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")
+)85YIV]WXVMRK
import requests
6IUYIWX&SH]
8VSRKL϶YLЎXXVЬRKLвTGɨGVIUYIWXRL4378498
XLRKG϶RXVY]АRHоPMЖYOLMVIUYIWXGɹXLВWмHдRKXLEQ
WР data чВXVY]АRHEXEPɱROɯQVIUYIWX:ɴHд
import requests
9TPSEHJMPI
import requests
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
6IWTSRWI
7EYOLMKМMGɨGTLRKXLиGXRKиRKчВVIUYIWXFϰRWЌ
GɹчРMXвRKXLYШGGPEWW Response ɇРMXвRKRɧ]GɹQШX
WРXLɺRKXMRRLWEY
status_code ,8847XEXYWWIVZIVXVϲZА
headers 'ɨGXLɺRKXMRLIEHIVQɧWIVZIVXVϲZАHЪM
HϰRK(MGXMSREV]
cookies 2ЎYWIVZIVGɹXVϲZАGSSOMIXLɳGɹXLВWм
HдRKXLYШGXɴRLRɧ]чВPϴ]GɨGGSSOMI
text 8VϲZАRШMHYRKVIWTSRWI
8LEQOLϲSZАGɨGXɴRLRʆRKOLɨGGжEXLZMЖR requests
XϰM[IFWMXIGLɴRLXLиGLXXTHSGWT]XLSRVIUYIWXWSVK
'LRK+ЮMIQEMPZЪM7184
7184PɧKMESXLиGKЮMQEMPXLɺRKHдRKLMЖRRE]4]XLSRLЦ
XVвQІGчКRLXLZMЖR smtplib HɽRKчВOЎXRРMчЎRQШX
71847IVZIVZɧKЮMIQEMP8Y]RLMɱRZMЖGWмHдRKXL
ZMЖRRɧ]WЌKɩ]OLɹOLʆRGLSZMЖGчКRLHϰRKZɧWмHдRK
RɱRGLɾRKXEWЌWмHдRKXLZMЖR sender PɧQШXXLZMЖR
KMɾTчКRLHϰRKZɧKЮMIQEMPчRKMϲRLR
'ɧMчІX sender
'ɧMчІXXк pip RLWEY
+ЮMIQEMPчRKMϲR
ɇВKЮMIQEMPZЪM sender FϰRG϶RGɹXɧMOLSϲRZɧQШXWР
XLɺRKXMRGжE71847IVZIVXVЪGOLMKЮM:ɴHдчSϰRGSHI
чВKЮMIQEMPXк71847IVZIVGжE%QE^SR
mail = Mail(
"smtp.gmail.com",
port = 465,
username = "[email protected]",
password = "yourpassword",
use_tls = False,
use_ssl = True,
debug_level = False
)
# Send message
mail.send(msg)
+ЮMIQEMPGɹчɴRLOɯQJMPI
&ϰRG϶RWмHдRKXLɱQGPEWW%XXEGLQIRXчВXϰS
EXXEGLQIRX
mail = Main(...)
msg = Message(..)
...
msg.attach(file01)
# Send message
mail.send(msg)
8ɳQLMВYXLɱQ
&ϰRGɹXLВXɳQLMВYXLɱQZАXLZMЖR sender XϰM[IFWMXI
GLɴRLXLиGXϰMчКEGLИLXXTWIRHIVVIEHXLIHSGWSVK
'LRK7SGOIX
TVSKVEQQMRK
'LRKRɧ]WЌZɴHдZMЖG\ɩ]HрRKQШXQɺMXVЬRK'PMIRX
7IVZIVWмHдRK7SGOIX7IVZIVWЌPϾRKRKLIXVɱRQШXTSVX
ZɧOLMGPMIRXOЎXRРMZɧSWЌXLɺRKFɨSLMВRXLК
XLɺRKXMRGжEGPMIRX -4Zɧ4SVX ZɧKЮMQIWWEKI\YРRK
GLSGPMIRX
7IVZIVWMHI
8ϰSJMPI server.py ZЪMRШMHYRKFɱRHЪM
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
ɇSϰRGSHIXVɱROLMXLрGXLMWЌGLϰ]ZɧPϾRKRKLIЮTSVX
8'41ЦMOLMGɹQШXOЎXRРMXкGPMIRXWЌLMЖRVE
XLɺRKFɨSOЎXRРMXк-4Zɧ4SVXRɧSZɴHд Got connection
from Got connection from ('192.168.1.104', 60018)
7EYчɹKЮMXVϲQШXQIWWEKIZЪMRШMHYRK Thank you for
connecting ZАGLSGPMIRX7EYчɹчɹRKOЎXRРMZЪMGPMIRX
'PMIRXWMHI
import socket
s = socket.socket()
host = '127.0.0.1'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
ɇSϰRGSHIXVɱRWЌOЎXRРMчЎRQШXWSGOIXWIVZIVXLɺRK
UYELSWXREQIPϴ]чвGXкTLRKXLиG
socket.gethostname() ZɧTSVX7EYOLMOЎXRРMWЌ
LMВRXLКVEOЎXUYϲXVϲZАXкWIVZIV7EYчɹXLɳчɹRKOЎXRРM