十二、 图形界面
1. 介绍
wxPython 基于wxWindows,跨平台
Tkinter Tk平台
PythonWin windows平台
Java Swing 只能用Jython
PyGTK GTK平台
wxpython Http://wxpython.org
Tkinter http://wiki.python.org/moin/TkInter
PythonWin http://starship.python.net/crew/mhammond
Java Swing http://java.sum.com/docs/books/tutorial/uiswing
PyGTK http://pygtk.org
PyQt http://wiki.python.org/moin/PyQt
3. 实践:
4. 代码:
5. 遇到问题处理:
wxPython库安装
解决:
6. 小结:
GUI
Python的GUI平台
wxPython
布局
事件处理
十三、 数据库支持
1. 介绍
Sqlite pysqlite
2. 官方帮助文档:
3. 实践:
4. 代码:
Importdata.py文件
import sqlite3
def convert(value):
if value.startwith('~'):
return value.strip('~')
if not value:
value = '0'
curs=conn.cursor()
create_tab='''
create table food (
id text primary key,
desc text,
water float,
kcal float,
protein float,
fat float,
ash float,
carbs float,
fiber float,
sugar float
)
'''
curs.execute(create_tab)
query='insert into food values(?,?,?,?,?,?,?,?,?,?)'
for line in open('ABBREV.txt'):
fields = line.split('^')
#field_count=fields.count()
vals = [convert(f) for f in fields[:10]]
curs.execute(query, vals)
conn.commit()
import sqlite3, sys
conn=sqlite3.connect('food.db')
curs=conn.cursor()
query='select * from food where %s' % sys.argv[1]
print(query)
curs.execute(query)
names=[f[0] for f in curs.description]
for row in curs.fetchall():
for pair in zip(names,row):
print '%s: %s' % pair
print
5. 遇到问题处理:
Pysqlite库 安装报错:
src/connection.h:26:20: fatal error: Python.h: No such file or directory
原因:缺少python 开发环境
解决:
For apt (Ubuntu, Debian...):
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
For yum (CentOS, RHEL...):
sudo yum install python-devel
For dnf (Fedora...):
sudo dnf install python2-devel # for python2.x installs
sudo dnf install python3-devel # for python3.x installs
For zypper (openSUSE...):
sudo zypper in python-devel # for python2.x installs
Python数据库变成接口
连接
游标
类型和特殊值
SQLite
函数:
Connect(…)
十四、 网络编程
1. 介绍
2. 官方帮助文档:
3. 实践:
Myserver1.py文件
import socket
s=socket.socket()
host='localhost'
print('hostname:'+host)
port =8888
s.bind((host, port))
s.listen(5)
while True:
c, addr=s.accept()
print 'Got connect from ',addr
c.send('connected')
c.close()
myclient.py文件
import socket
s=socket.socket()
host='localhost'
port=8888
s.connect((host,port))
print s.recv(1024)
>>> webpage=urlopen('http://www.python.org')
>>> import re
>>> text=webpage.read()
>>> m=re.search('<a href="([^"]+)" .*?>about</a>', text, re.IGNORECASE)
>>> m.group(1)
'/about/'
![](https://img-blog.csdn.net/20180228110156552?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZmVkZ2U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
>>> file=urlopen('file:/home/shilei/PycharmProjects/untitled2/log.log')
>>> text = file.read()
>>> text.strip()
'2018-01-11 14:55:09 PM - root - DEBUG -<input>: debug\n2018-01-11 14:55:09 PM - root - INFO -<input>: info\n2018-01-11 14:55:09 PM - root - WARNING -<input>: warning\n2018-01-11 14:55:09 PM - root - ERROR -<input>: error\n2018-01-11 14:55:09 PM - root - CRITICAL -<input>: critical\n2018-01-11 14:55:09 PM - root - DEBUG -<input>: log'
import socket, select
s=socket.socket()
host='localhost'
print('hostname:'+host)
port =8888
s.bind((host, port))
s.listen(5)
inputs = [s]
while True:
rs, ws, es = select.select(inputs, [], [])
for r in rs:
if r is s:
client_channel, addr = s.accept()
print 'Got connect from ', addr
inputs.append(client_channel)
client_channel.send('connected server')
else:
try:
data=r.recv(1024)
disconnected = not data
except socket.error:
disconnected = True
if disconnected:
print r.getpeername(), 'disconnected'
inputs.remove(r)
else:
import socket,random
s=socket.socket()
host='localhost'
port=8888
s.connect((host,port))
n=random.randrange(1,10)
s.send('client:'+str(n))
print 'client:'+str(n)
while True:
cmd=raw_input('enter quit(Q) send(S):')
cmd=cmd.strip().lower()
if cmd=='s':
s.send('I am '+str(n))
elif cmd=='q':
s.close()
break
except:
s.close()
实验6:
![](https://img-blog.csdn.net/20180228110912158?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZmVkZ2U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
MyHTMLParser.py文件
from urllib import urlopen
from HTMLParser import HTMLParser
class Scraper(HTMLParser):
in_h3=False
in_link=False
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag=='h3':
self.in_h3=True
if tag=='a' and 'href' in attrs:
self.in_link=True
self.chunks=[]
self.url=attrs['href']
def handle_data(self, data):
if self.in_link:
if tag=='h3':
self.in_h3=False
if tag=='a':
# if self.in_h3 and self.in_link:
if self.in_link:
print '%s (%s)' %(''.join(self.chunks), self.url)
#print('%(a) (%(b))').format({'a':''.join(self.chunks),'b':self.url})
def test():
text=urlopen('http://www.python.org/community/jobs').read()
parser=Scraper()
parser.feed(text)
parser.close()
if __name__=='__main__':
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
text=urlopen('http://www.python.org/community/jobs').read()
soup=BeautifulSoup(text)
jobs=set()
for header in soup('a'):
links=header('a','href')
if not links: continue
link=links[0]
jobs.add('%s (%s)' %(link.string, link['href']))
print '\n'.join(sorted(jobs,key=lambda s: s.lower()))
4. 遇到问题处理:
十六、 测试
1. 官方帮助文档:
2. 实践:
实验1:
![](https://img-blog.csdn.net/20180228111047100?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZmVkZ2U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
My_math.py文件
def square(x,y):
return x*y
MytestCase.py 文件
import unittest, my_math
class MytestCase(unittest.TestCase):
def testInteger(self):
for x in xrange(-10,10):
for y in xrange(-10,10):
p=my_math.square(x,y)
self.failUnless(p == x*y,'testInteger failed')
def testFloats(self):
for x in xrange(-10,10):
for y in xrange(-10,10):
x=x/10.0
y=y/10.0
p=my_math.square(x,y)
self.failUnless(p == x*y,'testFloats failed')
if __name__=='__main__':
4. 遇到问题处理:
5. 小结:
十七、 扩展Python
十八、 打包
1. 官方帮助文档:
2. 实践:
4. 遇到问题处理:
5. 小结:
十九、 日志记录
1. 官方帮助文档:
2. 实践:
实验1;
![](https://img-blog.csdn.net/20180228111224887?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZmVkZ2U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
MyReadConfig.py文件
from ConfigParser import ConfigParser
CONFIGFILE='python.txt'
config=ConfigParser()
config.read(CONFIGFILE)
print config.get('message','greeting')
radius=input(config.get('message','question')+'')
print config.get('message','result_message')
print config.getfloat('numbers','pi')*radius**2
[numbers]
pi:3.141592653589793
[message]
greeting:program
question:input radius?
result_message:this area is
import logging
logging.basicConfig(level=logging.INFO, filename='mylog.log')
logging.info('Start program')
logging.info('Trying to divide 1 by 0')
print 1/1
logging.info('The divide succeed')
logging.info('end')
3. 代码:
4. 遇到问题处理:
1. 介绍
wxPython 基于wxWindows,跨平台
Tkinter Tk平台
PythonWin windows平台
Java Swing 只能用Jython
PyGTK GTK平台
PyQt Qt平台,跨平台
wxpython Http://wxpython.org
Tkinter http://wiki.python.org/moin/TkInter
PythonWin http://starship.python.net/crew/mhammond
Java Swing http://java.sum.com/docs/books/tutorial/uiswing
PyGTK http://pygtk.org
PyQt http://wiki.python.org/moin/PyQt
3. 实践:
4. 代码:
5. 遇到问题处理:
wxPython库安装
报错:
解决:
6. 小结:
GUI
Python的GUI平台
wxPython
布局
事件处理
十三、 数据库支持
1. 介绍
Sqlite pysqlite
2. 官方帮助文档:
3. 实践:
4. 代码:
Importdata.py文件
import sqlite3
def convert(value):
if value.startwith('~'):
return value.strip('~')
if not value:
value = '0'
return float(value)
curs=conn.cursor()
create_tab='''
create table food (
id text primary key,
desc text,
water float,
kcal float,
protein float,
fat float,
ash float,
carbs float,
fiber float,
sugar float
)
'''
curs.execute(create_tab)
query='insert into food values(?,?,?,?,?,?,?,?,?,?)'
for line in open('ABBREV.txt'):
fields = line.split('^')
#field_count=fields.count()
vals = [convert(f) for f in fields[:10]]
curs.execute(query, vals)
conn.commit()
conn.close()
import sqlite3, sys
conn=sqlite3.connect('food.db')
curs=conn.cursor()
query='select * from food where %s' % sys.argv[1]
print(query)
curs.execute(query)
names=[f[0] for f in curs.description]
for row in curs.fetchall():
for pair in zip(names,row):
print '%s: %s' % pair
5. 遇到问题处理:
Pysqlite库 安装报错:
src/connection.h:26:20: fatal error: Python.h: No such file or directory
原因:缺少python 开发环境
解决:
For apt (Ubuntu, Debian...):
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
For yum (CentOS, RHEL...):
sudo yum install python-devel
For dnf (Fedora...):
sudo dnf install python2-devel # for python2.x installs
sudo dnf install python3-devel # for python3.x installs
For zypper (openSUSE...):
sudo zypper in python-devel # for python2.x installs
sudo zypper in python3-devel # for python3.x installs
6. 小结:Python数据库变成接口
连接
游标
类型和特殊值
SQLite
函数:
Connect(…)
十四、 网络编程
1. 介绍
2. 官方帮助文档:
3. 实践:
实验1:
Myserver1.py文件
import socket
s=socket.socket()
host='localhost'
print('hostname:'+host)
port =8888
s.bind((host, port))
s.listen(5)
while True:
c, addr=s.accept()
print 'Got connect from ',addr
c.send('connected')
c.close()
myclient.py文件
import socket
s=socket.socket()
host='localhost'
port=8888
s.connect((host,port))
print s.recv(1024)
实验2:
>>> webpage=urlopen('http://www.python.org')
>>> import re
>>> text=webpage.read()
>>> m=re.search('<a href="([^"]+)" .*?>about</a>', text, re.IGNORECASE)
>>> m.group(1)
'/about/'
>>> file=urlopen('file:/home/shilei/PycharmProjects/untitled2/log.log')
>>> text = file.read()
>>> text.strip()
'2018-01-11 14:55:09 PM - root - DEBUG -<input>: debug\n2018-01-11 14:55:09 PM - root - INFO -<input>: info\n2018-01-11 14:55:09 PM - root - WARNING -<input>: warning\n2018-01-11 14:55:09 PM - root - ERROR -<input>: error\n2018-01-11 14:55:09 PM - root - CRITICAL -<input>: critical\n2018-01-11 14:55:09 PM - root - DEBUG -<input>: log'
实验3:
实验4:
实验5:
import socket, select
s=socket.socket()
host='localhost'
print('hostname:'+host)
port =8888
s.bind((host, port))
s.listen(5)
inputs = [s]
while True:
rs, ws, es = select.select(inputs, [], [])
for r in rs:
if r is s:
client_channel, addr = s.accept()
print 'Got connect from ', addr
inputs.append(client_channel)
client_channel.send('connected server')
else:
try:
data=r.recv(1024)
disconnected = not data
except socket.error:
disconnected = True
if disconnected:
print r.getpeername(), 'disconnected'
inputs.remove(r)
else:
print data
import socket,random
s=socket.socket()
host='localhost'
port=8888
s.connect((host,port))
n=random.randrange(1,10)
s.send('client:'+str(n))
print 'client:'+str(n)
print s.recv(1024)
while True:
cmd=raw_input('enter quit(Q) send(S):')
cmd=cmd.strip().lower()
if cmd=='s':
s.send('I am '+str(n))
elif cmd=='q':
s.close()
break
except:
s.close()
实验6:
MyHTMLParser.py文件
from urllib import urlopen
from HTMLParser import HTMLParser
class Scraper(HTMLParser):
in_h3=False
in_link=False
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag=='h3':
self.in_h3=True
if tag=='a' and 'href' in attrs:
self.in_link=True
self.chunks=[]
self.url=attrs['href']
def handle_data(self, data):
if self.in_link:
self.chunks.append(data)
if tag=='h3':
self.in_h3=False
if tag=='a':
# if self.in_h3 and self.in_link:
if self.in_link:
print '%s (%s)' %(''.join(self.chunks), self.url)
#print('%(a) (%(b))').format({'a':''.join(self.chunks),'b':self.url})
def test():
text=urlopen('http://www.python.org/community/jobs').read()
parser=Scraper()
parser.feed(text)
parser.close()
if __name__=='__main__':
test()
实验7:
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
text=urlopen('http://www.python.org/community/jobs').read()
soup=BeautifulSoup(text)
jobs=set()
for header in soup('a'):
links=header('a','href')
if not links: continue
link=links[0]
jobs.add('%s (%s)' %(link.string, link['href']))
print '\n'.join(sorted(jobs,key=lambda s: s.lower()))
4. 遇到问题处理:
5. 小结:
十五、 Python web十六、 测试
1. 官方帮助文档:
2. 实践:
实验1:
My_math.py文件
def square(x,y):
return x*y
MytestCase.py 文件
import unittest, my_math
class MytestCase(unittest.TestCase):
def testInteger(self):
for x in xrange(-10,10):
for y in xrange(-10,10):
p=my_math.square(x,y)
self.failUnless(p == x*y,'testInteger failed')
def testFloats(self):
for x in xrange(-10,10):
for y in xrange(-10,10):
x=x/10.0
y=y/10.0
p=my_math.square(x,y)
self.failUnless(p == x*y,'testFloats failed')
if __name__=='__main__':
unittest.main()
3. 代码:4. 遇到问题处理:
5. 小结:
十七、 扩展Python
十八、 打包
1. 官方帮助文档:
2. 实践:
实践1:
4. 遇到问题处理:
5. 小结:
十九、 日志记录
1. 官方帮助文档:
2. 实践:
实验1;
MyReadConfig.py文件
from ConfigParser import ConfigParser
CONFIGFILE='python.txt'
config=ConfigParser()
config.read(CONFIGFILE)
print config.get('message','greeting')
radius=input(config.get('message','question')+'')
print config.get('message','result_message')
print config.getfloat('numbers','pi')*radius**2
[numbers]
pi:3.141592653589793
[message]
greeting:program
question:input radius?
result_message:this area is
实践2:
import logging
logging.basicConfig(level=logging.INFO, filename='mylog.log')
logging.info('Start program')
logging.info('Trying to divide 1 by 0')
print 1/1
logging.info('The divide succeed')
logging.info('end')
3. 代码:
4. 遇到问题处理:
5. 小结:
=================================================================
参考文献
《Python 基础教程(第2版.修订版)》 作者【挪】Magnus Lie Hetland
=================================================================