Python标准库03

本文主要介绍Python标准库。

1.shelve模块

写:

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python

import shelve

zhangsan = dict(zip(['name','age'],['zhangsan',24]))
lisi = dict(zip(['name','age'],['lisi',25]))

db = shelve.open('shelveDict')
db['zhangsan'] = zhangsan
db['lisi'] = lisi
db.close()

读:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python

import shelve

db = shelve.open('shelveDict')
print db['zhangsan']
print db['lisi']
db.close()
修改:
#!/usr/bin/env python

import shelve

db = shelve.open('shelveDict')
zhangsan = db['zhangsan']
zhangsan['name'] = 'zhangsanfeng'
db['zhangsan'] = zhangsan
print db['zhangsan']
db.close()

2.httplib模块

GET请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import httplib

class HttpRequestGETTest(object):
def __init__(self):
#self.body='{"UserName":"Admin","Password":"693aa8d0806c532115637809a863b1a3","sessionID":""}'
self.headers = {
"Referer": '192.168.1.1',
"Accept-Encoding": "gzip, deflate,sdch",
"Connection":"Keep-Alive"}

def http_get(self):
conn=httplib.HTTPConnection(host='192.168.1.1', port=80, strict=False, timeout=30)
conn.request(method='GET',url='/cgi-bin/GetLoginStatus?sessionID=undefined', body=None, headers=self.headers)
a = conn.getresponse().read()
print a

lianxi=HttpRequestGETTest()
lianxi.http_get()

POST请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import httplib

class HttpRequestPOSTTest(object):
def __init__(self):
self.body='{"UserName":"Admin","Password":"693aa8d0806c532115637809a863b1a3","sessionID":""}'
self.headers = {
"Referer": '192.168.1.1',
"Accept-Encoding": "gzip, deflate,sdch",
"Connection":"Keep-Alive"}

def http_post(self):
conn=httplib.HTTPConnection(host='192.168.1.1', port=80, strict=False, timeout=120)
conn.request(method='POST',url='/cgi-bin/Login', body=self.body, headers=self.headers)
self.session_id = conn.getresponse().read()
print self.session_id

lianxi=HttpRequestPOSTTest()
lianxi.http_post()

3.ftplib模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#coding: utf-8
from ftplib import FTP
import time
import tarfile
#!/usr/bin/python
#-*- coding: utf-8 -*-

from ftplib import FTP

def ftpconnect(host, username, password):
ftp = FTP()
#ftp.set_debuglevel(2) #打开调试级别2,显示详细信息
ftp.connect(host, 21) #连接
ftp.login(username, password) #登录,如果匿名登录则用空串代替即可
return ftp

def downloadfile(ftp, remotepath, localpath):
bufsize = 1024 #设置缓冲块大小
fp = open(localpath,'wb') #以写模式在本地打开文件
ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize) #接收服务器上文件并写入本地文件
ftp.set_debuglevel(0) #关闭调试
fp.close() #关闭文件

def uploadfile(ftp, remotepath, localpath):
bufsize = 1024
fp = open(localpath, 'rb')
ftp.storbinary('STOR '+ remotepath , fp, bufsize) #上传文件
ftp.set_debuglevel(0)
fp.close()

if __name__ == "__main__":
ftp = ftpconnect("******", "***", "***")
downloadfile(ftp, "***", "***")
uploadfile(ftp, "***", "***")

ftp.quit()

4.urllib模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
>>> import urllib
>>> f = urllib.urlopen('http://www.qq.com')
>>> f.getcode()
200
>>> f.geturl()
'http://www.qq.com'
>>> f.headers

------------------------------华丽的分割线-----------------------------

>>> filename = urllib.urlretrieve('http://www.google.com.hk/')
>>> type(filename)
<type 'tuple'>
>>> filename[0]
'/tmp/tmp8eVLjq'
>>> filename[1]
<httplib.HTTPMessage instance at 0xb6a363ec>
>>> urllib.urlcleanup()

------------------------------华丽的分割线-----------------------------

>>>filename=urllib.urlretrieve('http://www.qq.com',filename='./google.html')
>>> type(filename)
<type 'tuple'>
>>> filename[0]
'/home/dzhwen/python\xe6\x96\x87\xe4\xbb\xb6/Homework/urllib/google.html'
>>> filename[1]
<httplib.HTTPMessage instance at 0xb6e2c38c>

------------------------------华丽的分割线-----------------------------

>>> urllib.quote('http://www.baidu.com')
'http%3A//www.baidu.com'
>>> urllib.quote_plus('http://www.baidu.com')
'http%3A%2F%2Fwww.baidu.com'

------------------------------华丽的分割线-----------------------------

GET方法:
>>> import urllib
>>> params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> params
'eggs=2&bacon=0&spam=1'
>>> f=urllib.urlopen("http://python.org/query?%s" % params)
>>> print f.read()
POST方法:
>>> import urllib
>>> parmas = urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> f=urllib.urlopen("http://python.org/query",parmas)
>>> f.read()

5.hashlib模块

1
2
3
4
5
6
7
8
#!/usr/bin/env python
# coding:utf-8

import hashlib
rb = open('/root/test.txt','rb')
rb_md5 = hashlib.md5()
rb_md5.update(rb.read())
rb_md5.hexdigest()

6.tarfile模块

  • 使用tarfile压缩

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #!/usr/bin/env python
    # coding:utf-8

    import tarfile

    #创建压缩包名
    tar = tarfile.open("/tmp/tartest.tar.gz","w:gz")
    #创建压缩包
    for root,dir,files in os.walk("/tmp/tartest"):
    for file in files:
    fullpath = os.path.join(root,file)
    tar.add(fullpath)
    tar.close()
  • 使用tarfile解压

    1
    2
    3
    4
    5
    6
    7
    #!/usr/bin/env python
    # coding:utf-8

    import tarfile
    tar = tarfile.open("sample.tar.gz")
    tar.extractall()
    tar.close()
---------------- The End ----------------