Python Rat La Co Ban - Vo Duy Tuan 2
Python Rat La Co Ban - Vo Duy Tuan 2
helloworld.py
$ python helloworld.py
Hello world
a = 1
a = 1
a = 'Hello World'
a = [1, 2, 3]
a = [1.2, 'Hello', 'W', 2]
+
-
True False
not
and
or
< <=
> >= ==
!=
x = 2
in
not in
{ }
if condition1 :
indentedStatementBlockForTrueCondition1
elif condition2 :
indentedStatementBlockForFirstTrueCondition2
elif condition3 :
indentedStatementBlockForFirstTrueCondition3
elif condition4 :
indentedStatementBlockForFirstTrueCondition4
else:
indentedStatementBlockForEachConditionFalse
switch case
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!
while expression:
statement(s)
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
None
def sum(a, b):
return (a+b)
sum(1, 2)
(tr v gi tr l 3)
plus(2)
(kt qu tr v l 12)
sum(a,b) b a
sum(b = 1, a = 10)
"
'
str1 = "Hello"
str2 = 'world'
str1[0] str1[1]
paragraph = """This is line 1
This is line 2
This is line 3"""
[start:end] start
0 end
str = 'Hello world'
print str[0:4]
(Hin th "Hell")
print str[:4]
(Hin th "Hell")
print str[-3:]
(Hin th "rld")
print str[6:-3]
(Hin th "wo")
len(...)
find(str, beg=0
end=len(string)) 0
-1
print str.find('Bye');
(hin th -1)
find()
rfind()
split(str="", num=string.count(str))
splitlines()
strip([chars])
lstrip([chars])
rstrip([chars])
isnumeric()
lower()
upper()
[..]
numbers = [1, 2, 3, 4, 5]
names = ['Marry', 'Peter']
print numbers[0]
(Hin th 1)
print numbers[-3]
(Hin th 3)
print names[1]
(Hin th 'Peter')
len(array)
if index < len(array):
array[index]
else:
# handle this
try:
array[index]
except IndexError:
# handle this
in not in
[start:end] start
0 end
print numbers[:2]
(Hin th ['a', 'b'])
print numbers[-2:]
(Hin th ['c', 'd'])
del
numbers = [1, 2, 3, 4, 5]
del numbers[0]
print numbers
(Hin th [2, 3, 4, 5])
[start:end]
numbers = [1, 2, 3, 4, 5, 6, 7]
del numbers[2:4]
print numbers
(Hin th [1, 2, 5, 6, 7])
a = [1, 2]
b = [1, 3]
print a + b
(Hin th [1, 2, 1, 3])
list.append(newvalue)
newvalue list
numbers = [1, 2, 3]
numbers.append(4)
print numbers
(Hin th [1, 2, 3, 4]
list.pop()
numbers = [1, 2, 3]
mynumber = numbers.pop()
print mynumber
(Hin th 3)
print numbers
(Hin th [1, 2])
list.index(obj)
list.reverse()
list
numbers = [1, 2, 3, 4]
numbers.reverse()
print numbers
(Hin th [4, 3, 2, 1])
list.sort([func])
func
list
func()
0 -1 1
(...)
append() pop()
{...}
point = {'x': 1, 'y': 2}
dict[key] = value
dict.clear()
dict.copy()
dict.fromkeys(seq[, value])
value
dict.has_key(key)
dict.keys()
dict.values()
.py
.py
.dll
import random
random.__file__
(V d tr v '/usr/lib/python2.5/random.pyc')
dir(modulename)
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']
dir()
mymath.py
def cong(a, b):
return a + b
myexample.py
mymath.py
import mymath
num1 = 1
num2 = 2
.py
__init__.py
|-- mypack
| |-- __init__.py
| |-- mymodule1.py
| |-- mymodule2.py
|
mymodule1
import mypack.mymodule1
__init__.py
__init__.py
__init__.py
import mypack.mysubpack.mysubsubpack.module
class myclass([parentclass]):
assignments
def __init__(self):
statements
def method():
statements
def method2():
statements
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()
My Name is
Animal is running...
Animal is going...
My Name is Lucy
Dog is running...
Animal is going...
animal
animal
name age
__init__(self)
self
run() dog override
run() animal
fh = open(filepath, mode)
filepath mode
a
r+
w+
a+
f1 = open('test.txt', 'r')
f2 = open('access_log', 'a+'
open()
closed
mode
name
softspace
print
read([count])
f1 = open('test.txt', 'r')
data = f1.read();
read()
f2 = open('log.txt', 'r')
buffdata = f2.read(1024)
write()
f2 = open('access_log', 'a+')
f2.write('Attack detected')
close()
f1.close()
f2.close()
os.rename(old, new)
import os
os.rename('test.txt', 'test_new.txt')
os.remove(file)
import os
os.remove('test.txt')
os.mkdir(dir)
import os
os.mkdir('test')
os.rmdir(dir)
import os
os.rmdir('test')
os.listdir(dir)
dir
import os
allfiles = os.listdir('/root/downloads')
print allfiles
os
os
os.chdir(path)
os.getcwd()
os.chmod(path, mode)
os.makedirs(path[, mode])
os.removedirs(path)
os.path
os.path
os.path.exists(path)
os.path.getsize(path)
os.path.isfile(path)
os.path.isdir(path)
os.path.dirname(path)
os.path.getatime(path)
os.path.getmtime(path)
os.path.getctime(path)
from PIL import Image
Image
save(path, type)
...
im.save('photo_new.jpg', 'JPEG')
thumbnail
thumbnail
urllib2
json
import urllib2
import json
response = urllib2.urlopen('https://api.github.com/
users/voduytuan/repos')
data = json.load(response)
print data
import json
mystring = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
data = json.loads(mystring)
print data
(Hin th: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd
': 4})
import json
mydata = {
'name': 'John',
'age': 10
}
jsonstring = json.dumps(mydata)
print jsonstring
(hin th: {"age": 10, "name": "John"})
pip
lxml
xml
lxml
pip
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>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered
with strawberries and whipped cream</description>
<calories>900</calories>
</food>
</breakfast_menu>
'''
foods = soup.findAll('food')
for x in foods:
print x.find('name').string, ': ', x.price.stri
ng
Soup
findAll()
find()
x.price.string
xml
html
...
soup = Soup(websitehtml, 'html')
MySQLdb
pip
libmysqlclient.18.dylib
libmysqlclient.18.dylib /usr/lib/
$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18
.dylib /usr/lib/libmysqlclient.18.dylib
import MySQLdb
try
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
charset utf8
latin
utf8
...
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'test', charset = 'utf8'
)
cursor
import MySQLdb
cursor
tuple
Dictionary
import MySQLdb
cursor
exectute(sql) fetchone() fetchall()
fetchone()
None
fetchall()
fetchmany(size)
import MySQLdb
db = MySQLdb.connect(...)
db.close()
cursor
import MySQLdb
db = MySQLdb.connect(...)
cursor = db.cursor()
cursor.close()
db.close()
...
cur.execute("UPDATE Writers SET Name = %s WHERE Id
= %s", ("John", "4"))
...
%s
execute()
%s
pip
r = redis.StrictRedis(host='localhost', port=6379,
db=0)
import redis
r = redis.StrictRedis(...)
r.set('foo', 'bar')
print r.get('foo')
(Hin th 'bar')
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()
execute()
pip
import pylibmc
mc = pylibmc.Client(...)
mc.set('foo', 'bar')
print mc.get('foo')
(Hin th 'bar')
pika
pip
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()
hello
Hello World!
routing_key hello
hello
import pika
connection = pika.BlockingConnection(pika.Connectio
nParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.start_consuming()
connection
channel
basic_consume
hello callback()
pika
requests
pip
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")
GET
params get()
import requests
data
import requests
import requests
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
Response
status_code
headers
cookies
text
requests
smtplib
sender
sender
pip
sender
from sender import Mail, Message
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)
from sender import Mail, Message, Attachment
mail = Main(...)
msg = Message(..)
...
msg.attach(file01)
# Send message
mail.send(msg)
sender
server.py
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()
Got connection
from Got connection from ('192.168.1.104', 60018)
Thank you for
connecting
client.py
import socket
s = socket.socket()
host = '127.0.0.1'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
socket.gethostname()