├── .gitignore
├── .idea
├── Python.iml
├── misc.xml
├── modules.xml
├── vcs.xml
└── workspace.xml
├── .project
├── .pydevproject
├── .settings
└── org.eclipse.core.resources.prefs
├── Collections集合模块.py
├── Flask框架
├── Flask.py
├── MVC.py
└── templates
│ ├── form.html
│ ├── home.html
│ └── signin-ok.html
├── IO编程.py
├── ORM框架SQLAlchemy.py
├── Python基础
├── DataTypeConvert.py
├── Dictionary.py
├── List.py
├── String.py
├── class.py
├── for.py
├── function.py
├── ifelse.py
└── while.py
├── README.md
├── TCPIP.py
├── UDP.py
├── WSGI接口(原始).py
├── a.txt
├── b.txt
├── c.txt
├── dump.txt
├── test.db
├── 分布式进程.py
├── 多线程.py
├── 多进程.py
├── 实战-可怕的Python程序
├── LICENSE
│ └── README.txt
├── README.txt
├── backup
│ └── README.txt
├── conf
│ └── README.txt
└── www
│ ├── README.txt
│ ├── static
│ └── README.txt
│ └── templates
│ └── README.txt
├── 序列化.py
├── 数据库编程.py
├── 正则表达式.py
├── 错误_调试和测试.py
└── 面向对象.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | lib/
17 | lib64/
18 | parts/
19 | sdist/
20 | var/
21 | *.egg-info/
22 | .installed.cfg
23 | *.egg
24 |
25 | # PyInstaller
26 | # Usually these files are written by a python script from a template
27 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
28 | *.manifest
29 | *.spec
30 |
31 | # Installer logs
32 | pip-log.txt
33 | pip-delete-this-directory.txt
34 |
35 | # Unit test / coverage reports
36 | htmlcov/
37 | .tox/
38 | .coverage
39 | .cache
40 | nosetests.xml
41 | coverage.xml
42 |
43 | # Translations
44 | *.mo
45 | *.pot
46 |
47 | # Django stuff:
48 | *.log
49 |
50 | # Sphinx documentation
51 | docs/_build/
52 |
53 | # PyBuilder
54 | target/
55 |
--------------------------------------------------------------------------------
/.idea/Python.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
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 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | true
91 | DEFINITION_ORDER
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 | 1593054380117
269 |
270 |
271 | 1593054380117
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Python
4 |
5 |
6 |
7 |
8 |
9 | org.python.pydev.PyDevBuilder
10 |
11 |
12 |
13 |
14 |
15 | org.python.pydev.pythonNature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.pydevproject:
--------------------------------------------------------------------------------
1 |
2 |
3 | python 2.7
4 | Default
5 |
6 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//Flask\u6846\u67B6/Flask.py=utf-8
3 | encoding//Flask\u6846\u67B6/MVC.py=utf-8
4 | encoding/Collections\u96C6\u5408\u6A21\u5757.py=utf-8
5 | encoding/IO\u7F16\u7A0B.py=utf-8
6 | encoding/ORM\u6846\u67B6SQLAlchemy.py=utf-8
7 | encoding/TCPIP.py=utf-8
8 | encoding/UDP.py=utf-8
9 | encoding/WSGI\u63A5\u53E3(\u539F\u59CB).py=utf-8
10 | encoding/\u5206\u5E03\u5F0F\u8FDB\u7A0B.py=utf-8
11 | encoding/\u591A\u7EBF\u7A0B.py=utf-8
12 | encoding/\u591A\u8FDB\u7A0B.py=utf-8
13 | encoding/\u5E8F\u5217\u5316.py=utf-8
14 | encoding/\u6570\u636E\u5E93\u7F16\u7A0B.py=utf-8
15 | encoding/\u6B63\u5219\u8868\u8FBE\u5F0F.py=utf-8
16 | encoding/\u9519\u8BEF_\u8C03\u8BD5\u548C\u6D4B\u8BD5.py=utf-8
17 | encoding/\u9762\u5411\u5BF9\u8C61.py=utf-8
18 |
--------------------------------------------------------------------------------
/Collections集合模块.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # namedtuple()函数创建自定义的tuple
5 | from collections import namedtuple
6 | Point = namedtuple('Point', ['x', 'y'])
7 | p = Point(101, 2)
8 | print p.x
9 | print p.y
10 |
11 | # deque双端队列
12 | from collections import deque
13 | q = deque(['a', 'b', 'c'])
14 | q.append('x')
15 | q.appendleft('y')
16 | print q
17 |
18 | # defaultdict 无key时返回默认值
19 | from collections import defaultdict
20 | d = defaultdict(lambda : 'N/A')
21 | d['key1'] = 'abc'
22 | print d['key1']
23 | print d['key2']
24 |
25 | # OrderedDict 顺序key字典
26 | from collections import OrderedDict
27 | od = OrderedDict()
28 | od['oz'] = 2
29 | od['oc'] = 3
30 | od['oa'] = 1
31 | print od.keys()
32 |
33 | # Counter 简单计数器
34 | from collections import Counter
35 | c = Counter()
36 | for ch in 'programming':
37 | c[ch] += 1
38 | print c
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/Flask框架/Flask.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | from flask import Flask
5 | from flask import request
6 |
7 | app = Flask(__name__)
8 |
9 | @app.route('/', methods = ['GET', 'POST'])
10 | def home():
11 | return '
Home
'
12 |
13 | @app.route('/signin', methods = ['GET'])
14 | def signin_form():
15 | return ''''''
20 |
21 | @app.route('/signin', methods=['POST'])
22 | def signin():
23 | # 需要从request对象读取表单内容:
24 | if request.form['username']=='admin' and request.form['password']=='password':
25 | return 'Hello, admin!
'
26 | return 'Bad username or password.
'
27 |
28 | if __name__ == '__main__':
29 | app.run()
--------------------------------------------------------------------------------
/Flask框架/MVC.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | from flask import Flask, request, render_template
5 |
6 | app = Flask(__name__)
7 |
8 | @app.route('/', methods = ['GET', 'POST'])
9 | def home():
10 | return render_template('home.html')
11 |
12 | @app.route('/signin', methods = ['GET'])
13 | def signin_form():
14 | return render_template('form.html')
15 |
16 | @app.route('/signin', methods=['POST'])
17 | def signin():
18 | # 需要从request对象读取表单内容:
19 | username = request.form['username']
20 | password = request.form['password']
21 | if username == 'admin' and password == 'password':
22 | return render_template('signin-ok.html', username = username)
23 | return render_template('form.html', message = '用户名或密码错误', username = username)
24 |
25 |
26 | if __name__ == '__main__':
27 | app.run()
--------------------------------------------------------------------------------
/Flask框架/templates/form.html:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/Flask框架/templates/form.html
--------------------------------------------------------------------------------
/Flask框架/templates/home.html:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/Flask框架/templates/home.html
--------------------------------------------------------------------------------
/Flask框架/templates/signin-ok.html:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/Flask框架/templates/signin-ok.html
--------------------------------------------------------------------------------
/IO编程.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import logging
4 |
5 | # 打开文件
6 | try:
7 | f = open('a.txt', 'r') # 文件不存在,抛出IOError异常
8 | except IOError:
9 | print 'can not open file'
10 | else:
11 | try:
12 | print f.read() # 读文件失败,抛异常,需要在finally中关闭文件
13 | finally:
14 | print 'file.colse()'
15 | f.close()
16 | # with as 方法帮助调用 close 方法
17 | with open('b.txt', 'r') as ff:
18 | print ff.read()
19 | # read(size) 可以每次读size个字节
20 | # readline() 每次读取一行
21 | # readlines() 读取所有,按行返回一个list line.strip() 忽略末尾的 \n
22 | # 读取方式 rb 要读取非ASCII编码的文件,必须以二进制打开,在解码,如gbk文件
23 | with open('c.txt', 'rb') as fff:
24 | u = fff.read().decode('gbk')
25 | print u
26 | # 读文件是自动转码模块 codecs
27 | import codecs
28 | with codecs.open('c.txt', 'r', 'gbk') as ffff:
29 | print ffff.read()
30 |
31 | # 写文件
32 | # 区别在于 w wb
33 |
34 | # 操作文件和目录 os 模块 和 os.path 模块
35 | import os
36 | print os.name
37 | print os.environ # 返回dict
38 | print os.getenv('PATH')
39 | # 查看当前目录绝对路径
40 | p = os.path.abspath('.')
41 | print os.path.abspath('.')
42 | # 在某个路径下创建新目录
43 | absp = os.path.join(p, 'testdir') # 首先表示决定路径 创建路径
44 | print absp
45 | #os.mkdir(absp) # 然后创建出目录 如果存在 抛出异常
46 | # 删掉一个目录
47 | #os.rmdir(absp)
48 |
49 | # 拆分路径
50 | print os.path.split(absp) # 分为两部分,第二部分为最后级别及目录或文件名
51 | print os.path.splitext('G:\eclipse\Python\a.txt') # 获取文件扩展名
52 |
53 | # 重命名
54 | #os.rename('f.txt', 'a.txt')
55 |
56 | # 删除文件
57 | #os.remove('ee.txt')
58 |
59 | # 复制文件不在os模块 在 shutil 模块中
60 | import shutil
61 | shutil.copyfile('a.txt', 'm.txt')
62 |
63 | # 列出当前目录所有目录
64 | print [x for x in os.listdir('.') if os.path.isdir(x)]
65 |
66 | # 列出所有.py文件
67 | print [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py']
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/ORM框架SQLAlchemy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # 用于将数据库表结构用 对象表示出来
5 |
6 | # 导入
7 | from sqlalchemy import Column, String, create_engine
8 | from sqlalchemy.orm import sessionmaker, relationship
9 | from sqlalchemy.ext.declarative import declarative_base
10 | from sqlalchemy.sql.schema import ForeignKey
11 |
12 | # 创建对象的基类
13 | Base = declarative_base()
14 |
15 | # 定义User对象
16 | class User(Base):
17 | # 表的名字
18 | __tablename__ = 'user'
19 |
20 | # 表的结构
21 | id = Column(String(20), primary_key = True)
22 | name = Column(String(20))
23 |
24 | # 初始化数据库连接
25 | # 字符串表示连接信息:数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名
26 | engine = create_engine('mysql+mysqlconnector://root:wangh@localhost:3306/test')
27 | # 创建DBSession类型
28 | DBSession = sessionmaker(bind = engine)
29 | # 初始化完成
30 |
31 | # 添加记录
32 | # 创建session对象
33 | session = DBSession()
34 | # 创建User对象
35 | new_user = User(id = '5', name = 'Bob')
36 | # 添加到session
37 | session.add(new_user)
38 | # 提交及保存到数据库
39 | session.commit()
40 | # 关闭
41 | session.close()
42 |
43 | # 查询记录
44 | # 创建session
45 | session = DBSession()
46 | # 创建Query查询,filter是where条件,最后调用one 是返回为一行,all则返回所有行
47 | user = session.query(User).filter(User.id == '5').one()
48 | # 打印
49 | print 'type: ', type(user)
50 | print 'name: %s' % user.name
51 | session.close()
52 |
53 | # 如果一个User拥有多个Book,则可以对那个一一对多关系
54 | class User(Base):
55 | __tablename__ = 'user'
56 |
57 | id = Column(String(20), primary_key = True)
58 | name = Colum(String(2))
59 |
60 | # 一对多
61 | books = relationship('Book')
62 |
63 | class Book(Base):
64 | __tablename__ = 'book'
65 |
66 | id = Column(String(20), primary_key = True)
67 | name = Column(String(20))
68 | # ‘多’的一方book表是通过外键关联到user表
69 | user_id = Column(String(20)), ForeignKey('user.id')
70 | # 当我们查询一个User对象时,该对象的books属性将返回一个包含若干个Book对象的list,这会不会影响效率,因为我值查询User,可能并不关心Book
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/Python基础/DataTypeConvert.py:
--------------------------------------------------------------------------------
1 |
2 | a = int('123') # 转换为一个整数
3 | print(type(a))
4 |
5 | b = float('123.456')
6 | print(type(b))
7 |
8 | c = complex(2, 4)
9 | print(c)
10 |
11 | s = str(c)
12 | print(s)
13 |
14 | print(chr(65))
15 | print(ord('A'))
--------------------------------------------------------------------------------
/Python基础/Dictionary.py:
--------------------------------------------------------------------------------
1 |
2 | # 定义
3 | dic = {}
4 | dic['name'] = 'wangh'
5 | dic['age'] = 33
6 | dic['famle'] = '男'
7 | print(dic)
8 | dic1 = {
9 | 'name': 'kongl',
10 | 'age': 30,
11 | 'famle': '女',
12 | 'otherdic': {
13 | 'host': '123',
14 | 'ip': '192.168.1.1'
15 | }
16 | }
17 | print(dic1)
18 |
19 | # 根据key获取对象
20 | print(dic['name']) # wangh
21 | print(dic1['otherdic']['ip']) # 192.168.1.1
22 |
23 | # 常用操作字典的函数
24 | print(len(dic1)) # 字典元素个数,即key总数
25 | print(str(dic1)) # 输出字典可打印的字符串标识
26 | print(type(dic)) #
27 |
28 | # 字典常用方法
29 | dic2 = dic
30 | print('dic2,', dic2)
31 | dic.clear() # 删除所有元素,所有引用都变为空
32 | print(len(dic))
33 | print(dic2)
34 |
35 | dic3 = dic1.copy() # 返回字典的浅复制
36 | dic3['abc'] = 'aaa'
37 | print(dic3)
38 | print(dic1)
39 |
40 | l1 = ['a', 'b', 'c']
41 | dic4 = {}
42 | dic4 = dic4.fromkeys(l1) # 创建一个新字典,以序列的元素做字典的键,val为字典元素的初始值
43 | print(dic4)
44 |
45 | print(dic3.get('abc')) # 返回指定键的值,如果键未找到,则返回default指定的值
46 | print(dic3.get('ab', 'dddd'))
47 |
48 | print(dic3.setdefault('ab', '123')) # 与get类似,但如果键不存在,则会添加到字典中,并设置为默认值
49 | print(dic3)
50 |
51 | print(dic3.items()) # 以列表形式返回可遍历的(键, 值)元祖列表
52 |
53 | print(dic3.keys()) # 以列表形式返回字典的所有键
54 | print(dic3.values()) # 以列表形式返回字典的所有值
55 |
56 | dic3.update(dic4) # 把dic2的键值对更新到字典中
57 | print(dic3)
--------------------------------------------------------------------------------
/Python基础/List.py:
--------------------------------------------------------------------------------
1 |
2 | # 列表定义
3 | l1 = ['wangh', 'kongl', 'wanghjy']
4 | l2 = ['zhangs', l1]
5 |
6 | # 索引
7 | print(l1[0]) # wangh
8 | print(l1[1]) # kongl
9 | print(l1[-1]) # wanghjy
10 | print(l1[-2]) # kongl
11 | print(l2[1][1]) # kongl
12 |
13 | # 子集
14 | print(l1[1:2]) # ['kongl']
15 | print(l1[1:]) # ['kongl', 'wanghjy']
16 | print(l1[1:-1]) # ['kongl']
17 | print(l1[:-1]) # ['wangh', 'kongl']
18 |
19 | # 常用操作列表函数
20 | print(len(l1)) # 3
21 | print(max(l1)) # wanghjy
22 | print(min(l1)) # kongl
23 |
24 | # 列表常用方法
25 | l1.append('zhangs') # 末尾添加元素
26 | print(l1)
27 | print(l1.count('wangh')) # 1 某个元素在列表中的个数
28 | l1.extend(['123', '234']) # 列表末尾添加另一个列表的元素
29 | print(l1)
30 | print(l1.index('123')) # 4 找出元素第一次出现的索引
31 | l1.insert(4, '555') # 在指定位置插入元素
32 | print(l1)
33 | obj = l1.pop(-2) # 移除并返回列表中的元素,默认为最后一个元素
34 | print(obj) # 123
35 | print(l1)
36 | l1.remove('555') # 移除第一次出现的指定元素
37 | print(l1)
38 | l1.reverse() # 翻转列表
39 | print(l1)
40 | l1.sort() # 对列表进行排序
41 | print(l1)
--------------------------------------------------------------------------------
/Python基础/String.py:
--------------------------------------------------------------------------------
1 |
2 | # 字符串定义
3 | s1 = 'abcd'
4 | s2 = "abcd"
5 | s3 = 'a"b"cd' # 嵌套定义
6 |
7 | # 字符索引
8 | c1 = s1[0] # a
9 | c2 = s1[1] # b
10 | c3 = s1[-1] # d
11 | c4 = s1[-2] # c
12 |
13 | # 截取子串
14 | ss1 = s1[1:3] # bc
15 | ss2 = s1[1:] # bcd
16 | ss3 = s1[1:-1] # bc
17 | ss4 = s1[:-1] # abc
18 |
19 | # 常用方法
20 | s1 = " abc "
21 | print(s1.strip()) # 去除左右空白字符
22 | print(s1.lstrip()) # 去除左边空白字符
23 | print(s1.rstrip()) # 去除右边空白字符
24 | s2 = ',,,abc,,,'
25 | print(s2.strip(',')) # 去除左右指定字符
26 | print(s2.lstrip(',')) # 去除左边指定字符
27 | print(s2.rstrip(',')) # 去除右边指定字符
28 | l1 = ['first', 'second', 'three']
29 | print(s1.join(l1)) # 在参数列表项之间插入本字符串,若只有1项,则不插入
30 | print(s1.find('b')) # 查找字符,返回第一次找到时的索引
31 |
32 | # 字符串比较
33 | print('a' < 'b') # True
34 | print('ab' > 'b') # False
35 | print('ab' > 'aa') # True
36 | print('aa' == 'aa') # True
37 |
38 | # 获取字符串长度
39 | print(len('abc')) # 3
40 |
41 | # 字符串转换
42 | s1 = 'aBcDeF hIjKlM'
43 | print(s1.upper()) # 转换为大写
44 | print(s1.lower()) # 转换为小写
45 | print(s1.swapcase()) # 大小写互转
46 | print(s1.capitalize()) # 首字母大写,其余字符转为小写
47 |
48 | # 字符串分割
49 | s1 = 'abc,def,ghi'
50 | print(s1.split(',')) # 按指定字符分割,返回列表
51 |
--------------------------------------------------------------------------------
/Python基础/class.py:
--------------------------------------------------------------------------------
1 | # 定义:
2 | class Dog():
3 | """类文档注释"""
4 |
5 | __age = 0 # 定义类私有属性,以两个下划线开头
6 | name = 'lisi' # 定义类公共属性
7 |
8 | def __init__(self, name, age): # 构造函数,只能有一个
9 | self.name = name;
10 | self.age = age;
11 |
12 | # 定义类公共方法
13 | def func(self): # 每一个类方法第一个参数都是self 代表类实例本身,方法调用时自动传递
14 | print(self.name)
15 |
16 | # 定义类私有方法,以两个下划线开头
17 | def __func2(self):
18 | print(self.age)
19 |
20 |
21 |
22 | # 实例化:
23 | dog = Dog("w", 12);
24 | dog.name = "h"; # 怎么防止直接修改属性?
25 |
26 | # 继承:
27 | class Car():
28 | def __init__(self, name):
29 | self.name = name;
30 |
31 |
32 | class ECar(Car):
33 | def __init__(self, name):
34 | super.__init__(name); # 初始化父类
35 |
36 |
37 | #覆盖方法:
38 | # 子类定义父类同名函数
39 |
40 | # 动态属性需要继承object类
41 | class MyClass(object):
42 | def __init__(self):
43 | self.__param = None
44 | self.__param2 = None
45 |
46 | def getParam(self):
47 | print('getParam: %s' % self.__param)
48 | return self.__param
49 |
50 | def setParam(self, value):
51 | print('setParam: %s' % self.__param)
52 | self.__param = value
53 |
54 | def delParam(self):
55 | print('delParam: %s' % self.__param)
56 | del self.__param
57 |
58 | param = property(getParam, setParam, delParam)
59 |
60 | # 方法2:使用@property修饰
61 |
62 | @property # getter
63 | def param2(self):
64 | print('get param2: %s' % self.__param2)
65 | return self.__param2
66 |
67 | @param2.setter
68 | def param2(self, value):
69 | print('set param2: %s' % self.__param2)
70 | self.__param2 = value
71 |
72 | @param2.deleter
73 | def param2(self):
74 | print('del param2: %s' % self.__param2)
75 | del self.__param2
76 |
77 | if __name__ == '__main__':
78 | cls = MyClass()
79 | cls.param = 10 # setParam
80 | print('current cls.param: %s' % cls.param) # getParam
81 | del cls.param # delParam
82 |
83 | cls.param2 = 101 # setter
84 | print('current cls.param2: %s' % cls.param2) # getter
85 | del cls.param2 # deleter
--------------------------------------------------------------------------------
/Python基础/for.py:
--------------------------------------------------------------------------------
1 |
2 | l1 = ['wangh', 'kongl', 'wangjy']
3 |
4 | for name in l1:
5 | print(name)
6 |
7 | l2 = range(10)
8 | for i in l2:
9 | print(i)
--------------------------------------------------------------------------------
/Python基础/function.py:
--------------------------------------------------------------------------------
1 |
2 | def f01(a, b, c):
3 | print('a, b, c', a, b, c)
4 | a2, b2, c2 = a + c, b * 2, c ** 2
5 | return a2, b2, c2
6 |
7 | x, y, z = f01(1, 2, 3)
8 | print('x, y, z', x, y, z)
9 |
10 | x, y, z = f01(x, y, z)
11 | print('x, y, z', x, y, z)
12 |
13 | import functools
14 |
15 | def add(a, b):
16 | return a + b
17 |
18 | # 生成新函数,添加的参数从左到右依次填充
19 | plus1 = functools.partial(add, 4)
20 |
21 | ret1 = plus1(6) # 10
22 | ret2 = plus1(7) # 11
23 |
24 | print(ret1)
25 | print(ret2)
26 |
27 | # lambda
28 |
29 | fun = lambda x, y : x * y
30 | print(fun(4, 5)) # 20
31 |
32 |
--------------------------------------------------------------------------------
/Python基础/ifelse.py:
--------------------------------------------------------------------------------
1 |
2 | x, y, z = 10, 5, 5
3 | if x > y:
4 | print('x > y')
5 | elif x < y:
6 | print('x < y')
7 | else:
8 | print('x = y')
--------------------------------------------------------------------------------
/Python基础/while.py:
--------------------------------------------------------------------------------
1 |
2 | x = 10
3 | while x > 0:
4 | print(x)
5 | x -= 1
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python
2 |
3 | Python知识点归纳项目
4 | hello 测试下
5 |
--------------------------------------------------------------------------------
/TCPIP.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | import socket
5 | import threading, time
6 |
7 | type = 'clident'
8 | if type == 'client':
9 | # 创建socket AF_INET IPV4 AF_INET6 IPV6
10 | address = ('127.0.0.1', 9999)
11 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 | # 建立连接:
13 | s.connect(address)
14 | # 接收欢迎消息:
15 | print s.recv(1024)
16 | for data in ['Michael', 'Tracy', 'Sarah']:
17 | # 发送数据:
18 | s.send(data)
19 | print s.recv(1024)
20 | s.send('exit')
21 | s.close()
22 |
23 | else:
24 | def tcplink(sock, addr):
25 | print 'Accept new connect from %s:%s...' % addr
26 | sock.send('Welcome')
27 | while True:
28 | data = sock.recv(1024)
29 | time.sleep(5)
30 | if data == 'exit' or not data:
31 | break
32 | sock.send('Hello %s' % data)
33 | sock.close()
34 | print 'Connection from %s:%s closed' % addr
35 |
36 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
37 | # 监听端口
38 | s.bind(('0.0.0.0', 9999))
39 | s.listen(5)
40 | print 'waiting for connect...'
41 | while True:
42 | # 接收一个新连接
43 | sock, addr = s.accept()
44 | # 创建新线程处理
45 | t = threading.Thread(target = tcplink, args = (sock, addr))
46 | t.start()
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/UDP.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | import socket
5 |
6 | address = ('127.0.0.1', 9999)
7 |
8 | type = 'serdver'
9 | if type == 'server':
10 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
11 | s.bind(address)
12 | print 'Bind UDP on 9999...'
13 | while True:
14 | data, addr = s.recvfrom(1024)
15 | print 'Receive from %s:%s' % addr
16 | s.sendto('Hello %s' % data, addr)
17 |
18 | else:
19 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
20 | for data in ['wangh', 'kongl', 'yee']:
21 | s.sendto(data, address)
22 | print s.recv(1024)
23 | s.close()
--------------------------------------------------------------------------------
/WSGI接口(原始).py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # 实现必须的函数
5 | def application(environ, start_response):
6 | start_response('200 OK', [('Content-Type', 'text/html')])
7 | return 'Hello,World
'
8 |
9 | # 导入WSGI模块
10 | from wsgiref.simple_server import make_server
11 | # 创建一个服务器
12 | httpd = make_server('', 8000, application)
13 | print 'Servint HTTP on Port 8000...'
14 | # 开启监听
15 | httpd.serve_forever()
--------------------------------------------------------------------------------
/a.txt:
--------------------------------------------------------------------------------
1 | 爱上的方式地方
--------------------------------------------------------------------------------
/b.txt:
--------------------------------------------------------------------------------
1 | 大噶速度过dsfgd!@#$
--------------------------------------------------------------------------------
/c.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/c.txt
--------------------------------------------------------------------------------
/dump.txt:
--------------------------------------------------------------------------------
1 | (dp1
2 | S'age'
3 | p2
4 | I20
5 | sS'score'
6 | p3
7 | I80
8 | sS'name'
9 | p4
10 | S'Bob'
11 | p5
12 | s.
--------------------------------------------------------------------------------
/test.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/test.db
--------------------------------------------------------------------------------
/分布式进程.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import multiprocessing
4 |
5 | # multiprocessing 的 子模块 managers 将网络通讯封装,可以静默升级 在同一台机器上的 多进程程序,如 只需要将 Queue 通过managers暴露在网上即可
6 |
7 | type = 'd'
8 | if type == 'server':
9 | # 服务器端,负责创建Queue,发布到网络,并向其中写任务,但是分布式的 Queue不能直接拿到,需要通过manager.get_task_queue()获得Queue
10 | # 在windows 上跑不了 服务端
11 | import random, time, Queue
12 | from multiprocessing.managers import BaseManager
13 |
14 | # 发送任务的队列
15 | task_queue = Queue.Queue()
16 | # 接收结果的队列
17 | result_queue = Queue.Queue()
18 |
19 | # 从BaseManager 继承的QueueManager
20 | class QueueManager(BaseManager):
21 | pass
22 |
23 | # 把两个queue注册到网络
24 | QueueManager.register('get_task_queue', callable = lambda : task_queue)
25 | QueueManager.register('get_result_queue', callable = lambda : result_queue)
26 | # 绑定端口5000,验证码'abc'
27 | manager = QueueManager(address = ('', 5000), authkey = 'abc')
28 | # 启动queue
29 | manager.start()
30 | # 获得通过网络访问的Queue的对象
31 | task = manager.get_task_queue()
32 | result = manager.get_result_queue()
33 | # 放入任务
34 | for i in range(10):
35 | n = i #random.randint(0, 10000)
36 | print 'Put task %d...' % n
37 | task.put(n)
38 | # 从result读取结果
39 | print 'Try get results...'
40 | for i in range(10):
41 | r = result.get(timeout = 10)
42 | print 'Result: %s' % r
43 | # 关闭
44 | manager.shutdown()
45 |
46 | else:
47 | # 客户端
48 | import time, sys, Queue
49 | from multiprocessing.managers import BaseManager
50 |
51 | # 创建雷类似的QueueManager
52 | class QueueManager(BaseManager):
53 | pass
54 | # 由于这个QueueManager只能从网络拿到,所以注册是提供名字
55 | QueueManager.register('get_task_queue')
56 | QueueManager.register('get_result_queue')
57 | # 连接到服务器
58 | server_addr = '192.168.1.108'
59 | print 'Connect to server %s...' % server_addr
60 | # 端口和验证码要正确
61 | m = QueueManager(address = (server_addr, 5000), authkey = 'abc')
62 | # 从网络连接
63 | m.connect()
64 | # 获取Queue对象
65 | task = m.get_task_queue()
66 | result = m.get_result_queue()
67 | # 从task去除任务,处理并返回结果
68 | for i in range(10):
69 | try:
70 | n = task.get(timeout = 5)
71 | print 'run task %d * %d...' % (n, n)
72 | r = '%d * %d = %d' % (n, n, n * n)
73 | time.sleep(1)
74 | result.put(r)
75 | except Queue.Empty:
76 | print 'task queue is empty'
77 | #处理结束
78 | print 'exit'
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
--------------------------------------------------------------------------------
/多线程.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # 低级模块 thread 高级模块 threading(常用)
5 | import threading, time
6 |
7 | # 线程执行代码
8 | def loop():
9 | print 'thread %s is running...' % threading.current_thread().name
10 | n = 0
11 | while n < 5:
12 | n += 1
13 | print 'thread %s >>> %s' % (threading.current_thread().name, n)
14 | time.sleep(1)
15 | print 'thread %s end' % threading.current_thread().name
16 |
17 | if __name__ == '__main__':
18 | print 'thread %s is running...' % threading.current_thread().name
19 | t = threading.Thread(target = loop, name = 'LoopThread')
20 | t.start()
21 | t.join()
22 | print 'thread %s end' % threading.current_thread().name
23 |
24 | # 锁 lock = threading.Lock() lock.acquire() lock.release
25 |
26 | # ThreadLocal 解决不同线程处理同一个对象时 免去 传参 及 全局变量的方式、 常用于:每个线程绑定一个数据库连接,HTTP请求,用户身份信息等
27 | # 创建全局ThreadLocal对象
28 | local_school = threading.local()
29 |
30 | def process_student():
31 | print 'Hello %s (in %s)' % (local_school.student, threading.current_thread().name)
32 |
33 | def process_thread(name):
34 | # 绑定TrheadLocal的student
35 | local_school.student = name
36 | process_student()
37 |
38 | t1 = threading.Thread(target = process_thread, args = ('wangh',), name = 'ThreadA')
39 | t2 = threading.Thread(target = process_thread, args = ('kongl',), name = 'ThreadB')
40 | t1.start()
41 | t2.start()
42 | t1.join()
43 | t2.join()
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/多进程.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # os 模块封装了 fock() 函数,但只适用于Unix/Mac 系统,且只能是Linux版的 Python 才有os.fork()函数
5 |
6 | import os
7 |
8 | if os.name == 'posix':
9 | print 'Process (%s) start...' % os.getpid()
10 | pid = os.fork()
11 | if pid == 0: # 子进程
12 | print "I'm child process (%s) and my parent is (%s)" % (os.getpid(), os.getppid())
13 | else:
14 | print 'I (%s) just create a child process (%s)' % (os.getpid(), pid)
15 |
16 | # 跨平台的 多进程模块 multiprocessing
17 | from multiprocessing import Process
18 | import os
19 |
20 | #子进程要执行的代码
21 | def run_proc(name):
22 | print 'Run child process %s (%s)...' % (name, os.getpid())
23 |
24 | if __name__ == '__main__':
25 | print 'Parent process %s' % os.getpid()
26 | #创建进程
27 | p = Process(target = run_proc, args = ('test',))
28 | print 'Process will start'
29 | p.start()
30 | p.join() # 等待子进程的结束
31 | print 'Process end'
32 |
33 | # 进程池
34 | #进程池的大小,默认等于处理器的 核心数,可改变 p = pool(5)
35 | from multiprocessing import Pool
36 | import os, random, time
37 |
38 | def long_time_task(name):
39 | print 'Run task %s (%s)' % (name, os.getpid())
40 | start = time.time()
41 | time.sleep(random.random() * 3)
42 | end = time.time()
43 | print 'Task %s runs %0.2f seconds' % (name, (end - start))
44 |
45 | if __name__ == '__main__':
46 | print 'Parent process %s' % os.getpid()
47 | p = Pool(9)
48 | for i in range(5):
49 | p.apply_async(long_time_task, args = (i,))
50 | print 'Wait for all subprocess done...'
51 | p.close() # close 后进不能在加入process
52 | p.join()
53 | print 'All subprocess end...'
54 |
55 | # 进程间通讯 Queue 或 Pipes
56 | from multiprocessing import Process, Queue
57 | import os, random, time
58 |
59 | def write(q):
60 | for value in ['a', 'b', 'c']:
61 | print 'Put %s to queue...' % value
62 | q.put(value)
63 | time.sleep(4)
64 |
65 | def read(q):
66 | while True:
67 | value = q.get(True)
68 | print 'Get %s from queue...' % value
69 |
70 | if __name__ == '__main__':
71 | # 父进程创建queue,并传给子进程
72 | q = Queue()
73 | pw = Process(target = write, args = (q,))
74 | pr = Process(target = read, args = (q,))
75 | # 启动写进程
76 | pw.start()
77 | # 启动读进程
78 | pr.start()
79 | # 等待结束
80 | pw.join()
81 | # 死循环强行结束
82 | pr.terminate()
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
--------------------------------------------------------------------------------
/实战-可怕的Python程序/LICENSE/README.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/实战-可怕的Python程序/LICENSE/README.txt
--------------------------------------------------------------------------------
/实战-可怕的Python程序/README.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/实战-可怕的Python程序/README.txt
--------------------------------------------------------------------------------
/实战-可怕的Python程序/backup/README.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/实战-可怕的Python程序/backup/README.txt
--------------------------------------------------------------------------------
/实战-可怕的Python程序/conf/README.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/实战-可怕的Python程序/conf/README.txt
--------------------------------------------------------------------------------
/实战-可怕的Python程序/www/README.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/实战-可怕的Python程序/www/README.txt
--------------------------------------------------------------------------------
/实战-可怕的Python程序/www/static/README.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/实战-可怕的Python程序/www/static/README.txt
--------------------------------------------------------------------------------
/实战-可怕的Python程序/www/templates/README.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heyxiaohao/Python/14a1f7a1108c69fbebe9f0dd454db5d54d5b0db3/实战-可怕的Python程序/www/templates/README.txt
--------------------------------------------------------------------------------
/序列化.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # 简单文件及不重要数据 序列化和反序列化模块 cPickle 或 pickle
5 | try:
6 | import cPickle as pickle
7 | except ImportError:
8 | import pickle
9 |
10 | d = dict(name = 'Bob', age = 20, score = 80)
11 | print d
12 | s = pickle.dumps(d)
13 | print s
14 | with open('dump.txt', 'w') as f:
15 | f.write(s)
16 |
17 | with open('dump.txt', 'r') as fread:
18 | rs = fread.read()
19 | rd = pickle.loads(rs)
20 | print rd
21 |
22 | with open('dump.txt', 'r') as fread:
23 | print pickle.load(fread)
24 |
25 | # 重要数据 使用 JSON 模块 保存,也适用于不同 语言的传递
26 | print '---------------'
27 | import json
28 | d = dict(name = 'Wangh', age = 20, score = 80)
29 | json_str = json.dumps(d)
30 | print json_str
31 |
32 | json_d = json.loads(json_str)
33 | print json_d
34 | # 注:反序列化得到的字符串是unicode 需要转换 为str
35 |
36 | # 将类序列化需要 自己编写默认序列化函数
37 | class A(object):
38 | def __init__(self, name, age):
39 | self.name = name
40 | self.age = age
41 |
42 | def serial(self):
43 | return {
44 | 'name' : self.name,
45 | 'age' : self.age
46 | }
47 |
48 | a = A('kongl', 24)
49 | json_str = json.dumps(a, default=A.serial)
50 | print json_str
51 | print json.dumps(a, default = lambda obj : obj.__dict__) # 推荐此种方式,则不需要定义函数,但要排除 __slots__ 的class
52 |
53 | def dict2obj(d):
54 | return A(d['name'], d['age'])
55 |
56 | b = json.loads(json_str, object_hook = dict2obj)
57 | print b.name
58 | print b.age
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/数据库编程.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | type = 'MySQL'
5 |
6 | if type == 'sqlite3':
7 | # 导入驱动
8 | import sqlite3
9 | # 连接到数据库 test.db 如果文件不存在,则会自动创建
10 | conn = sqlite3.connect('test.db')
11 | # 创建一个cursor
12 | cursor = conn.cursor()
13 | # 执行创建表
14 | cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
15 | # 执行插入数据
16 | cursor.execute("insert into user (id, name) values ('1', 'wangh')")
17 | # 通过rowcount获取影响的行数
18 | print cursor.rowcount
19 | # 关闭cursor
20 | cursor.close()
21 | # 提交事物
22 | conn.commit()
23 | # 关闭connection
24 | conn.close()
25 |
26 | conn1 = sqlite3.connect('test.db')
27 | cursor1 = conn1.cursor()
28 | # 执行查询语句
29 | cursor1.execute("select * from user where id=?", '1')
30 | # 获取结果集
31 | value = cursor1.fetchall()
32 | print value
33 | cursor1.close()
34 | conn1.close()
35 |
36 | elif type == 'MySQL':
37 | import mysql.connector
38 |
39 | conn = mysql.connector.connect(user = 'root', password = 'qidian', database = 'test', use_unicode = True)
40 | cursor = conn.cursor()
41 | #cursor.execute("create table user (id varchar(20) primary key, name varchar(20))")
42 | # 插入记录 MySQL的占位符为 %s
43 | for i in range(20,32,1):
44 | cursor.execute('select * from user')
45 | values=cursor.fetchall()
46 | # print values
47 | flag=0
48 | for j in range(0,values.__len__(),1):
49 | strData =filter(str.isdigit,values[j][0].encode("utf-8"))
50 | if int(strData)==i:
51 | print values[j][0]
52 | flag=1
53 | if flag!=1:
54 | cursor.execute('insert into user(id, name) values(%s, %s)', [i, 'kongl'])
55 | print '插入成功'
56 | print cursor.rowcount # 打印影响的行数
57 | else:
58 | print '已有数据'
59 | # print cursor.rowcount #打印影响的行数
60 | conn.commit()
61 | cursor.close()
62 |
63 | # 查询
64 | cursor = conn.cursor()
65 | for i in range(0,10,1):
66 | cursor.execute('select * from user where id = %s' % i)# where id = %s' % '1')
67 | values = cursor.fetchall()
68 | print values
69 | cursor.close()
70 | conn.close()
71 | else:
72 | pass
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/正则表达式.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # 1 如果直接给出字符,则表示精确匹配
5 | # 2 \d 表示数字, \w 表示字母或数字, . 可以匹配任意字符,\s 表示空白符,包括Tab
6 | # 3 * 表示任意长度,+ 表示至少一个字符,? 表示0或1个字符,{n} 表示n个字符,{n,m} 表示n到m个字符
7 | # 如 \d{3}\s+\d{3,8}
8 | # - 是特殊字符,需要\转义 \-
9 |
10 | # 更精确的匹配范围 表示 []
11 | # 如 [0-9a-zA-Z\_] 可以匹配一个数字,字母,或者下划线
12 | # A|B 可以匹配A,B
13 | # ^ 表示行的开头, ^\d 表示必须以数字开头
14 | # $ 表示行的结束,\d$ 表示必须以数字结束
15 |
16 | # re 模块
17 | # r作为字符串的前缀,可省略转义
18 | import re
19 |
20 | print re.match(r'^\d{3}\-\d{3,8}$', '010-12345')
21 | print re.match(r'^\d{3}\-\d{3,8}$', '010 12345')
22 |
23 | # 切割字符串功能比纯字符串更强
24 | print 'a b c'.split(' ')
25 | print re.split(r'\s+', 'a b c')
26 | print re.split(r'[\s\,]+', 'a, b c,, c')
27 |
--------------------------------------------------------------------------------
/错误_调试和测试.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # 错误处理机制 try except finally
5 | print '-----错误处理-----'
6 |
7 | try:
8 | r = 10 / 1
9 | print 'try...'
10 | except ZeroDivisionError, e:
11 | print e
12 | else: # else 语句块 在没有错误时执行
13 | print 'else...'
14 | finally:
15 | print 'finally...'
16 | print 'End'
17 |
18 | # 错误基类 BaseException
19 |
20 | print '使用内置logging模块打印错误信息'
21 | import logging
22 | logging.basicConfig(level=logging.INFO)
23 |
24 | def foo(s):
25 | return 10 / int(s)
26 |
27 | def bar(s):
28 | return foo(s) * 2
29 |
30 | def main():
31 | try:
32 | bar('0')
33 | except StandardError, e:
34 | print e
35 | logging.exception(e) # 可以打印出堆栈信息
36 | main()
37 | print 'End'
38 |
39 | # 抛出错误 raise 可以抛出错误对象,也可以单独使用 raise 用于将错误抛出,供上层处理
40 | def func1(s):
41 | return 10 / int(s)
42 | def func2(s):
43 | try:
44 | func1(s)
45 | except ZeroDivisionError:
46 | print 'Error'
47 | raise
48 |
49 | def main():
50 | try:
51 | func2('0')
52 | except ZeroDivisionError, e:
53 | logging.exception(e)
54 | main()
55 | print '---------------'
56 |
57 | print '-----调试-----'
58 | # 使用 print
59 | # 使用断言, -O 参数关闭断言
60 | try:
61 | n = 0
62 | assert (n != 0) # 抛出AssertError异常
63 | except AssertionError, e:
64 | logging.exception(e)
65 | else:
66 | 10 / n
67 | # 使用logging模块
68 | print '---------------'
69 | # import logging
70 | # logging.basicConfig(level=logging.INFO)
71 | s = '0'
72 | n = int(s)
73 | logging.info('n = %d' % n)
74 | print 10 / n
75 |
76 | print '-------------'
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/面向对象.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | from _ast import Num
4 |
5 | class Student(object): # object 是所有对象的基类
6 | def __init__(self, name, score, id): # 构造函数
7 | self.name = name
8 | self.score = score
9 | self.__id = id # 成员变量前加 __ 表示私有变量,无法从外部访问
10 |
11 | def print_score(self):
12 | print '%s, %s' % (self.name, self.score)
13 | @property
14 | def id(self):
15 | return self.__id
16 | @id.setter
17 | def id(self, id):
18 | self.id = id
19 |
20 | bart = Student('Bart', 95.0, 1) # 实例化类
21 | list = Student('List', 87.1, 2)
22 | bart.print_score() # 成员函数调用
23 | list.print_score()
24 | bart.sex = '女' # 可以动态的添加属性,但是只对当前对象有效
25 | print bart.sex
26 | # print list.sex # 抛出异常AttributeError
27 |
28 | print bart.name
29 | #print bart.__id # 抛出异常AttributeError
30 | print bart.id
31 |
32 | class Animal(object):
33 | def run(self):
34 | print 'Animal is running...'
35 |
36 | class Dog(Animal):
37 | def run(self): # 覆盖父类方法
38 | print 'Dog is running...'
39 |
40 | def __len__(self): # 要获取自定义类型的len方法 需要自己编写 __len__()函数
41 | return 3
42 |
43 | class Cat(Animal):
44 | def run(self):
45 | print 'Cat is running...'
46 |
47 | class Tortoise(Animal):
48 | def run(self):
49 | print 'Tortoise is running...'
50 |
51 | dog = Dog()
52 | cat = Cat()
53 | dog.run()
54 | cat.run()
55 |
56 | def run_(animal):
57 | animal.run()
58 |
59 | run_(Dog())
60 | run_(Cat())
61 | run_(Tortoise())
62 |
63 |
64 | # 获取对象信息
65 | print '---获取对象信息---'
66 | print type(123)
67 | print type('abc')
68 | print type([])
69 | print type(str)
70 | print type(Animal)
71 | print type(dog)
72 |
73 | # 每一种内置类型都在 types 模块有定义
74 | import types
75 | print type(123) == types.IntType
76 | print type(Animal) == types.TypeType
77 |
78 | # 判断类型 isinstance()
79 | print '---isinatance()---'
80 | print isinstance(dog, Animal)
81 | print isinstance(dog, (Dog, Animal)) # 可以判断是否是中的一种类型
82 |
83 | # 获取对象的所有属性和方法
84 | print '---dir()---'
85 | print dir(dog)
86 |
87 | print len(dog)
88 |
89 | # getattr() setattr() hasattr()
90 | try:
91 | print hasattr(bart, name)
92 | except NameError:
93 | pass
94 |
95 | # 可以动态的给对象绑定属性
96 | class A(object):
97 | pass
98 | print '---动态绑定属性---'
99 | a = A()
100 | b = A()
101 | a.name = 'abc' # 仅对当前对象有效
102 | print a.name
103 | try:
104 | print b.name
105 | except AttributeError:
106 | pass
107 | print '---动态绑定方法---'
108 | def set_age(self, age): # 定义方法体
109 | self.age = age
110 | from types import MethodType # 导入模块方法
111 | a.set_age = MethodType(set_age, a, A) # 此方式只对当前实例有效
112 | a.set_age(24)
113 | print a.age
114 |
115 | # 对所有实例都有效的动态绑定方法的方式 给类绑定
116 | def set_score(self, score):
117 | self.score = score
118 | A.set_score = MethodType(set_score, None, A)
119 | b.set_score(54)
120 | print b.score
121 |
122 | # 限制动态创建属性 __slots__ 变量 只对当前类有效,对子类无效
123 | print '---限制---'
124 | class B(object):
125 | __slots__ = ('name', 'age')
126 | c = B()
127 | c.name = 'ad'
128 | c.age = 12
129 | try:
130 | c.score = 'adf'
131 | except AttributeError:
132 | print 'AttributeError'
133 |
134 | # @property 装饰器 将方法变为属性,可通过直接属性调用,并可检测参数值
135 | print '---@property---'
136 | class C(object):
137 | def __init__(self):
138 | self.__score = 10
139 |
140 | def __len__(self):
141 | return 9
142 |
143 | @property # 只定义它,就只有getter
144 | def score(self):
145 | return self.__score
146 |
147 | @score.setter
148 | def score(self, value):
149 | if not isinstance(value, int):
150 | raise ValueError('score must be integer!')
151 | if value < 0 or value > 100:
152 | raise ValueError('score must be between 0 ~ 100')
153 | self.__score = value
154 |
155 | cc = C()
156 | cc.score = 60
157 | print cc.score
158 | try:
159 | cc.score = 9999
160 | print cc.score
161 | except ValueError:
162 | print 'ValueError'
163 |
164 | print len(cc)
165 |
166 | # Python 支持多重继承
167 |
168 | # 类 内置属性
169 | print '类内置属性'
170 | # __repr__ 打印实例的地址,但是对于用户而言无用,因此自定义__str__方法,让__repr__ = __str__
171 | class D(object):
172 | def __init__(self, name):
173 | self.name = name
174 |
175 | def __str__(self):
176 | return 'D object (name = %s)' % self.name
177 | __repr__ = __str__
178 |
179 | print D('wangh')
180 | # 如果需要将类 作为可迭代的对象,需要实现__iter__(self) 及 next(self) 方法
181 | class E(object):
182 | def __init__(self):
183 | self.a = 0
184 | self.b = 1
185 |
186 | def __iter__(self):
187 | return self
188 |
189 | def next(self):
190 | tmp = self.b
191 | self.b = self.a + self.b
192 | self.a = tmp
193 | # self.a, self.b = self.b, self.a + self.b # 先计算在加上 同上
194 | if self.a > 100000:
195 | raise StopIteration()
196 | return self.a
197 |
198 | def __getitem__(self, n): # 使类可以使用索引取值, 但是需要对传入的参数做类型判断,如切片 isinstance(n, slice)
199 | a, b = 1, 1
200 | for x in range(n):
201 | a, b = b, a + b
202 | return a
203 | # 还有负数等 与之对应的方法__setitem__ __delitem__
204 |
205 | for n in E():
206 | print n
207 |
208 | print E()[10]
209 | # 对实例进行调用 需要实现 __call__ 方法
210 | class F(object):
211 | def __init__(self, num):
212 | self.num = num
213 |
214 | def __call__(self):
215 | return 'Num = %d' % self.num
216 |
217 | f = F(123)
218 | print f()
219 | # callable 函数 可以判断 对象是否可以被调用
220 | print callable(f)
221 |
222 | # 使用 type()函数动态创建类
223 | print '使用 type()函数动态创建类'
224 | # 先定义函数
225 | def fn(self, name = 'world'):
226 | print 'Hello %s' % name
227 | Hello = type('Hello', (object,), dict(hello = fn)) # 创建Hello class
228 | h = Hello()
229 | h.hello()
230 | # 要创建类 type() 需要传入三个参数
231 | # 1 class 的名称
232 | # 2 继承的父类集合,如果只有一个 记住 元祖的 ,
233 | # 3 方法名和函数绑定
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
--------------------------------------------------------------------------------