├── .gitattributes ├── README.md ├── aogorithm ├── __init__.py └── hanoi.py ├── asyn_io ├── __init__.py ├── asyn_aiohttp.py ├── asyn_async_await.py ├── asyn_asyncio.py └── asyn_coroutines.py ├── base_demo ├── 2.txt ├── __init__.py ├── __pycache__ │ ├── test1.cpython-36.pyc │ ├── test12.cpython-36.pyc │ ├── test25_decorate.cpython-36.pyc │ └── test5.cpython-36.pyc ├── test01_reduce.py ├── test02_shuffle.py ├── test03_re.py ├── test04_urllib_request.py ├── test05_fib.py ├── test06_look_04.py ├── test07_input.py ├── test08_work_is_fat.py ├── test09_range.py ├── test10_sum.py ├── test11_hex.py ├── test12_math.py ├── test13_math_quadratic.py ├── test14_args.py ├── test15_work_product.py ├── test16_recursive.py ├── test17_trim.py ├── test18_Iterable.py ├── test19_work_k_v.py ├── test20_reduce.py ├── test21_filter.py ├── test22_sorted.py ├── test23_return.py ├── test24_lambda.py ├── test25_decorate.py ├── test26_partial.py ├── test27_use_modules.py ├── test28_path.py ├── test29_serialize.py ├── test30_json.py └── test31_regex.py ├── commonlib ├── __init__.py ├── code.png ├── lib_base64.py ├── lib_collections.py ├── lib_contextlib.py ├── lib_datetime.py ├── lib_hashlib.py ├── lib_hmac.py ├── lib_htmlparse.py ├── lib_itertools.py ├── lib_struct.py └── lib_urllib.py ├── db ├── __init__.py ├── db_mysql.py ├── db_orm_SQLAlchemy.py └── db_sqlite.py ├── django ├── __init__.py └── django_inner_fields.py ├── error_and_debug ├── __init__.py ├── demo01_try.py ├── demo2_logging.py ├── demo3_log.py ├── demo4_debug.py ├── demo5_mydict.py └── demo6_setUp_tearDown.py ├── ex_lib ├── __init__.py ├── ball.bmp ├── ex_lib_chardet.py ├── ex_lib_pillow.py ├── ex_lib_psutils.py ├── ex_lib_pygame.py ├── ex_lib_pyqt.py └── ex_lib_requests.py ├── gui_demo ├── demo1.py └── demo2.py ├── img ├── custom_class_1.png ├── custom_class_2.png ├── custom_class_3.png ├── distribute_process_error01.png ├── distribute_process_error02.png ├── distribute_process_ok01.png ├── err_01.png ├── err_02.png ├── local_file_server.png ├── logo.png ├── logo_thumbnail.png └── logo_thumbnail_blur.png ├── multitask ├── __init__.py ├── test01_multi_progress.py ├── test02_sub_progress.py ├── test03_queue.py ├── test04_distribute_process_1.py └── test05_distribute_process_2.py ├── my_res └── idea_active_proxy.exe ├── oop_demo ├── __init__.py ├── student.py ├── test01.py ├── test02.py ├── test03_property.py ├── test04_extend.py ├── test05_custom_class.py ├── test06_enum.py ├── test07_metaclass.py └── test08_orm.py ├── other_tools ├── __init__.py ├── file_utils.py ├── send_email.py ├── urllib_download_big_file.py ├── urllib_read.py ├── virtualenv.py └── weather_city.json ├── requests_demo ├── requests_demo_01.py └── requests_demo_sample.py ├── static ├── FlaskDemo.py ├── location_file_server.py └── yield_demo.py ├── test ├── __init__.py ├── test01_unittest01.py ├── test02_unittest02.py ├── test03_path.py ├── test04_game.py ├── test05_closure.py ├── test06_aes.py ├── test07.py └── test08_sort.py ├── web ├── __init__.py ├── flask_demo_base.py ├── flask_demo_login.py ├── flask_demo_mvc.py ├── my_res │ ├── sina.html │ ├── web_form.html │ ├── web_tcp_demo.png │ ├── web_udp_demo.png │ ├── wsgi_01.png │ └── wsgi_02.png ├── templates │ ├── web_home.html │ ├── web_login.html │ └── web_ok.html ├── web_tcp_client.py ├── web_tcp_demo.py ├── web_tcp_server.py ├── web_udp_client.py ├── web_udp_server.py ├── web_wsgi_demo1.py └── web_wsgi_demo_server1.py ├── web_spider ├── __init__.py ├── demo1.py └── get.py └── work ├── __init__.py ├── auto_increment_student.py ├── closure.py ├── decorator.py ├── exception.py ├── file_io.py ├── findMinAndMax.py ├── io_file.py ├── io_r_w.py ├── map_reduce.py ├── palindrome.py ├── screen.py ├── serialize_and_json.py ├── student.py ├── unittest_student.py ├── work_async_await.py ├── work_bmpinfo.py ├── work_datetime.py ├── work_db_sqlite.py ├── work_doctest.py ├── work_hmac.py ├── work_html_parse.py ├── work_itertools.py ├── work_md5.py ├── work_md5_salt.py ├── work_regex.py ├── work_urllib.py └── yanghui_triangles.py /.gitattributes: -------------------------------------------------------------------------------- 1 | *.js linguist-language=python 2 | *.css linguist-language=python 3 | *.html linguist-language=python 4 | *.png linguist-language=python 5 | *.jpg linguist-language=python -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PythonDemo 2 | 3 | 廖雪峰老师博客上的所有练习和作业都包含在该项目中了 4 | 5 | 另外有一些额外拓展的demo 6 | 7 | 如果你觉得不错或者对你有帮助,请帮我点个star吧 8 | -------------------------------------------------------------------------------- /aogorithm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/aogorithm/__init__.py -------------------------------------------------------------------------------- /aogorithm/hanoi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-17 16:58:55 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : 1 7 | """ 8 | 汉诺塔算法 9 | """ 10 | 11 | # 第一个塔为初始塔,中间的塔为借用塔,最后一个塔为目标塔 12 | i = 0 # 记录步数 13 | 14 | 15 | def move(no, come, to): # 将编号为no的盘子由come移动到to 16 | global i 17 | i += 1 18 | print("第", i, " 步:将 ", no, " 号盘子 ", come, "---->", to) 19 | 20 | 21 | def hanoi(no, come, denpend_on, to): # 将no个盘子由初始塔移动到目标塔(利用借用塔) 22 | if no == 1: 23 | move(1, come, to) # 只有一个盘子是直接将初塔上的盘子移动到目的地 24 | else: 25 | hanoi(no - 1, come, to, denpend_on) # 先将初始塔的前no - 1个盘子借助目的塔移动到借用塔上 26 | move(no, come, to) # 将剩下的一个盘子移动到目的塔上 27 | hanoi(no - 1, denpend_on, come, to) # 最后将借用塔上的no - 1个盘子移动到目的塔上 28 | 29 | 30 | if __name__ == '__main__': 31 | print("请输入盘子的个数:") 32 | no = input() 33 | print(no) 34 | print("盘子移动情况如下:\n") 35 | hanoi(int(no), 'A塔', 'B塔', 'C塔') 36 | -------------------------------------------------------------------------------- /asyn_io/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 -------------------------------------------------------------------------------- /asyn_io/asyn_aiohttp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/27 0027. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | asyncio可以实现单线程并发IO操作。 9 | 10 | 如果仅用在客户端,发挥的威力不大。 11 | 如果把asyncio用在服务器端,由于HTTP连接就是IO操作,因此可以用单线程+coroutine实现多用户的高并发支持。 12 | 13 | asyncio实现了TCP、UDP、SSL等协议, 14 | aiohttp则是基于asyncio实现的HTTP框架。 15 | 16 | """ 17 | 18 | # 编写一个web服务器用来处理url 19 | # 1. / 首页返回 b'

Index

' 20 | # 2. /hello/{name} - 根据URL参数返回文本hello, %s! 21 | import asyncio 22 | from aiohttp import web 23 | 24 | 25 | async def index(request): 26 | await asyncio.sleep(1) 27 | return web.Response(body=b'

Index

', content_type='text/html') 28 | 29 | 30 | async def hello(request): 31 | await asyncio.sleep(1) 32 | text = '

hello, %s!

' % request.match_info["name"] 33 | return web.Response(body=text.encode("utf-8"), content_type='text/html') 34 | 35 | 36 | async def init(loop): 37 | my_app = web.Application(loop=loop) 38 | my_app.router.add_route("GET", "/", index) 39 | my_app.router.add_route("GET", "/hello/{name}", hello) 40 | srv = await loop.create_server(my_app.make_handler(), "", 80) 41 | print("Server started...") 42 | return srv 43 | 44 | 45 | # aiohttp的初始化函数init()也是一个coroutine,loop.create_server()则利用asyncio创建TCP服务。 46 | loop = asyncio.get_event_loop() 47 | loop.run_until_complete(init(loop)) 48 | loop.run_forever() 49 | 50 | """ 51 | web.Response(self, *, body=None, status=200,reason=None, text=None, headers=None, content_type=None, charset=None) 52 | 廖老师的不标记内容类型的话,默认是下载,可以加上content_type='text/html' 53 | 54 | http://127.0.0.1/ 55 |

Index

56 | 57 | http://127.0.0.1/hello 58 | 404: Not Found 59 | 60 | http://127.0.0.1/hello/TaoYuan 61 |

hello, TaoYuan!

62 | """ 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /asyn_io/asyn_async_await.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/27 0027. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | Python从3.5版本开始为asyncio提供了async和await的新语法 9 | 10 | 用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型 11 | 然后在coroutine内部用yield from调用另一个coroutine实现异步操作 12 | 13 | 为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读。 14 | 15 | 请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换: 16 | 1. 把@asyncio.coroutine替换为async; 17 | 2. 把yield from替换为await。 18 | 19 | 注意新语法只能用在Python 3.5以及后续版本 20 | 之前版本则仍需使用asyncio案例的方案。 21 | """ 22 | import asyncio 23 | 24 | 25 | # 之前代码 26 | @asyncio.coroutine 27 | def hello1(): 28 | print("hello1!") 29 | # 异步调用asyncio.sleep(1) 30 | r = yield from asyncio.sleep(1) 31 | print("hello1等待结束,返回:", r) 32 | 33 | 34 | # 新代码 更加简洁易懂了 35 | async def hello2(): 36 | print("hello2!") 37 | # 异步调用asyncio.sleep(1) 38 | r = await asyncio.sleep(1) 39 | print("hello2等待结束,返回:", r) 40 | 41 | 42 | # get EventLoop 43 | loop = asyncio.get_event_loop() 44 | # exec coroutine 45 | loop.run_until_complete(asyncio.wait([hello1(), hello2()])) 46 | loop.close() 47 | 48 | """ 49 | 返回结果仍然是一致的,使用也不受影响 50 | 51 | hello1! 52 | hello2! 53 | hello1等待结束,返回: None 54 | hello2等待结束,返回: None 55 | """ 56 | -------------------------------------------------------------------------------- /asyn_io/asyn_asyncio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。 9 | 10 | asyncio的编程模型就是一个消息循环。 11 | 我们从asyncio模块中直接获取一个EventLoop的引用 12 | 然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。 13 | 14 | 1. asyncio提供了完善的异步IO支持; 15 | 16 | 2. 异步操作需要在coroutine中通过yield from完成; 17 | 18 | 3. 多个coroutine可以封装成一组Task然后并发执行。 19 | """ 20 | import asyncio 21 | import threading 22 | from datetime import datetime 23 | 24 | # @asyncio.coroutine 25 | # def hello(): 26 | # print("hello!") 27 | # # 异步调用asyncio.sleep(1) 28 | # r = yield from asyncio.sleep(1) 29 | # print("等待结束,返回:", r) 30 | 31 | 32 | # # get EventLoop 33 | # loop = asyncio.get_event_loop() 34 | # # exec coroutine 35 | # loop.run_until_complete(hello()) 36 | # loop.close() 37 | 38 | 39 | """ 40 | @asyncio.coroutine把一个generator标记为coroutine类型 41 | 然后,我们就把这个coroutine扔到EventLoop中执行 42 | 43 | hello() 首先执行print("hello!") 44 | 然后,yield from语法可以让我们方便地调用另一个generator 45 | 46 | 由于asyncio.sleep()也是一个coroutine 47 | 所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环 48 | 当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(None),然后继续执行下一行语句 49 | 50 | 把asyncio.sleep(1)看成是一个耗时1秒的IO操作 51 | 此时,主线程并未等待,而是去执行EventLoop中其他可以执行的coroutine了,因此可以实现并发执行。 52 | 53 | """ 54 | 55 | 56 | # 对上面的demo用两个coroutine进行改造实验 57 | @asyncio.coroutine 58 | def hello(): 59 | print("hello {} {}".format(datetime.now(), threading.currentThread())) 60 | r = yield from asyncio.sleep(1) 61 | print("end {} {}".format(datetime.now(), threading.currentThread())) 62 | 63 | 64 | # get EventLoop 65 | # loop = asyncio.get_event_loop() 66 | # # exec coroutine 67 | # test_task = [hello(), hello()] 68 | # loop.run_until_complete(asyncio.wait(test_task)) 69 | # loop.close() 70 | 71 | """ 72 | hello 2017-12-27 10:54:18.648749 <_MainThread(MainThread, started 9512)> 73 | hello 2017-12-27 10:54:18.648749 <_MainThread(MainThread, started 9512)> 74 | (暂停约1秒) 75 | end 2017-12-27 10:54:19.648806 <_MainThread(MainThread, started 9512)> 76 | end 2017-12-27 10:54:19.648806 <_MainThread(MainThread, started 9512)> 77 | 78 | 由打印的当前线程名称可以看出,两个coroutine是由同一个线程并发执行的。 79 | 80 | 如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行。 81 | """ 82 | 83 | 84 | # 我们用asyncio的异步网络连接来获取sina、sohu和163的网站首页 85 | @asyncio.coroutine 86 | def wget(host): 87 | print("wget {}".format(host)) 88 | connect = asyncio.open_connection(host, 80) 89 | reader, writer = yield from connect 90 | header = 'GET / HTTP/1.0\r\nHost: {}\r\n\r\n'.format(host) 91 | writer.write(header.encode("utf-8")) 92 | yield from writer.drain() 93 | while True: 94 | line = yield from reader.readline() 95 | if line == b'\r\n': 96 | break 97 | print("{} header:{}".format(host, line.decode("utf-8").rstrip())) 98 | # Ignore the body, close the socket 99 | writer.close() 100 | 101 | 102 | loop = asyncio.get_event_loop() 103 | tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']] 104 | loop.run_until_complete(asyncio.wait(tasks)) 105 | loop.close() 106 | 107 | """ 108 | 可见3个连接由一个线程通过coroutine并发完成。 109 | 110 | wget www.sina.com.cn 111 | wget www.163.com 112 | wget www.sohu.com 113 | www.sina.com.cn header:HTTP/1.1 200 OK 114 | www.sina.com.cn header:Server: nginx 115 | www.sina.com.cn header:Date: Wed, 27 Dec 2017 03:36:07 GMT 116 | www.sina.com.cn header:Content-Type: text/html 117 | www.sina.com.cn header:Content-Length: 603812 118 | www.sina.com.cn header:Connection: close 119 | www.sina.com.cn header:Last-Modified: Wed, 27 Dec 2017 03:33:15 GMT 120 | www.sina.com.cn header:Vary: Accept-Encoding 121 | www.sina.com.cn header:Expires: Wed, 27 Dec 2017 03:37:03 GMT 122 | www.sina.com.cn header:Cache-Control: max-age=60 123 | www.sina.com.cn header:X-Powered-By: shci_v1.03 124 | www.sina.com.cn header:Age: 3 125 | www.sina.com.cn header:Via: http/1.1 ctc.ningbo.ha2ts4.97 (ApacheTrafficServer/6.2.1 [cHs f ]), http/1.1 ctc.xiamen.ha2ts4.41 (ApacheTrafficServer/6.2.1 [cHs f ]) 126 | www.sina.com.cn header:X-Via-Edge: 1514345767204779d11da3cd64cde2eeece4f 127 | www.sina.com.cn header:X-Cache: HIT.41 128 | www.sina.com.cn header:X-Via-CDN: f=edge,s=ctc.xiamen.ha2ts4.41.nb.sinaedge.com,c=218.17.157.119;f=Edge,s=ctc.xiamen.ha2ts4.41,c=222.76.214.41 129 | www.163.com header:HTTP/1.0 302 Moved Temporarily 130 | www.163.com header:Server: Cdn Cache Server V2.0 131 | www.163.com header:Date: Wed, 27 Dec 2017 03:36:07 GMT 132 | www.163.com header:Content-Length: 0 133 | www.163.com header:Location: http://www.163.com/special/0077jt/error_isp.html 134 | www.163.com header:Connection: close 135 | www.sohu.com header:HTTP/1.1 200 OK 136 | www.sohu.com header:Content-Type: text/html;charset=UTF-8 137 | www.sohu.com header:Connection: close 138 | www.sohu.com header:Server: nginx 139 | www.sohu.com header:Date: Wed, 27 Dec 2017 03:35:10 GMT 140 | www.sohu.com header:Cache-Control: max-age=60 141 | www.sohu.com header:X-From-Sohu: X-SRC-Cached 142 | www.sohu.com header:Content-Encoding: gzip 143 | www.sohu.com header:FSS-Cache: HIT from 9730790.17464048.11067740 144 | www.sohu.com header:FSS-Proxy: Powered by 3373701.4749967.4710554 145 | """ -------------------------------------------------------------------------------- /asyn_io/asyn_coroutines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | 协程 9 | 10 | 优势 11 | 1. 最大的优势就是协程极高的执行效率。因为不用切换线程 12 | 2. 不需要多线程的锁机制,因为只有一个线程,也不存在同时写变量冲突 13 | 在协程中控制共享资源不加锁,只需要判断状态就好了,所以执行效率比多线程高很多。 14 | 15 | Python对协程的支持是通过generator实现的: 16 | 在generator中,我们不但可以通过for循环来迭代 17 | 还可以不断调用next()函数获取由yield语句返回的下一个值。 18 | 但是Python的yield不但可以返回一个值,它还可以接收调用者发出的参数。 19 | 20 | 执行顺序如下: 21 | come produce 22 | come consumer 23 | # 以上只执行一次,然后进入循环收发 24 | [生产者] 生产了1 25 | [消费者] 消费了1 26 | [生产者] 消费者返回了OK 27 | 28 | 29 | consumer函数是一个generator,把一个consumer传入produce后: 30 | 31 | 1. 调用c.send(None)启动生成器 32 | 2. 一旦生产了东西,通过c.send(n)切换到consumer执行 33 | 3. consumer通过yield拿到消息,处理,又通过yield把结果传回 34 | 4. produce拿到consumer处理的结果,继续生产下一条消息 35 | 5. produce决定不生产了,通过c.close()关闭consumer,整个过程结束 36 | 整个流程无锁,由一个线程执行,produce和consumer协作完成任务,所以称为“协程”,而非线程的抢占式多任务。 37 | 38 | """ 39 | 40 | 41 | def consumer(): 42 | r = "" 43 | print("come consumer") 44 | while True: 45 | n = yield r 46 | if not n: 47 | return 48 | print("[消费者] 消费了{}".format(n)) 49 | r = "OK" 50 | 51 | 52 | def produce(csm): 53 | print("come produce") 54 | csm.send(None) 55 | n = 0 56 | while n < 5: 57 | n += 1 58 | print("[生产者] 生产了{}".format(n)) 59 | r = csm.send(n) 60 | print("[生产者] 消费者返回了{}".format(r)) 61 | csm.close() 62 | 63 | 64 | if __name__ == '__main__': 65 | c = consumer() 66 | produce(c) 67 | 68 | -------------------------------------------------------------------------------- /base_demo/2.txt: -------------------------------------------------------------------------------- 1 | 123 2 | 321 3 | 1234567 -------------------------------------------------------------------------------- /base_demo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/base_demo/__init__.py -------------------------------------------------------------------------------- /base_demo/__pycache__/test1.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/base_demo/__pycache__/test1.cpython-36.pyc -------------------------------------------------------------------------------- /base_demo/__pycache__/test12.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/base_demo/__pycache__/test12.cpython-36.pyc -------------------------------------------------------------------------------- /base_demo/__pycache__/test25_decorate.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/base_demo/__pycache__/test25_decorate.cpython-36.pyc -------------------------------------------------------------------------------- /base_demo/__pycache__/test5.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/base_demo/__pycache__/test5.cpython-36.pyc -------------------------------------------------------------------------------- /base_demo/test01_reduce.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | if __name__ == '__main__': 4 | # 一行代码实现对列表a中的偶数位置的元素进行加3后求和? 5 | a = [1, 2, 3, 4, 5] 6 | print(reduce(lambda x, y: x + y, [a[x] + (x + 1) % 2 * 3 for x in range(0, 5)])) 7 | -------------------------------------------------------------------------------- /base_demo/test02_shuffle.py: -------------------------------------------------------------------------------- 1 | from random import shuffle 2 | 3 | if __name__ == '__main__': 4 | # 将列表a的元素顺序打乱,再对a进行排序得到列表b,然后把a和b按元素顺序构造一个字典d。 5 | a = [1, 2, 3, 4, 5] 6 | # 将列表a的元素顺序打乱 7 | shuffle(a) 8 | 9 | # 再对a进行排序得到列表b 10 | b = sorted(a, reverse=True) 11 | 12 | # 然后把a和b按元素顺序构造一个字典d。 13 | d = dict(zip(a, b)) 14 | 15 | print(d) 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /base_demo/test03_re.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def test(filename, num=1): 5 | # 'Find Top Frequent Words:' 6 | fp = open(filename, 'r') 7 | text = fp.read() 8 | fp.close() 9 | 10 | lst = re.split('[0-9\W]+', text) 11 | 12 | # create words set, no repeat 13 | words = set(lst) 14 | d = {} 15 | for word in words: 16 | d[word] = lst.count(word) 17 | del d[''] 18 | 19 | result = [] 20 | for key, value in sorted(d.iteritems(), key=lambda k_v: (k_v[1], k_v[0]), reverse=True): 21 | result.append((key, value)) 22 | return result[:num] 23 | 24 | 25 | if __name__ == '__main__': 26 | # readlines与xreadlines区别 27 | test('./' 28 | '2.txt', 10) 29 | # f = open("2.txt") 30 | # f.close() 31 | # print(f.readlines()) 32 | # print(f.xreadlines()) 33 | -------------------------------------------------------------------------------- /base_demo/test04_urllib_request.py: -------------------------------------------------------------------------------- 1 | import urllib.request 2 | 3 | request = urllib.request.Request('http://www.baidu.com/') 4 | response = urllib.request.urlopen(request) 5 | if response.getcode() != 200: 6 | print("None!") 7 | else: 8 | html = response.read() 9 | # 如果返回结果不为空 10 | if html is not None: 11 | # html = html.decode("utf-8") 12 | filename = 'C:\\Users\\Administrator\\Desktop\\test.html' 13 | file = open(filename, 'wb') 14 | file.write(html) 15 | file.close() 16 | # print(html) 17 | else: 18 | print("Maybe The Program is Error!") 19 | 20 | # 头信息 21 | print(response.info()) 22 | -------------------------------------------------------------------------------- /base_demo/test05_fib.py: -------------------------------------------------------------------------------- 1 | # 输出斐波那契数列 2 | import sys 3 | 4 | 5 | def fib(n): 6 | a, b = 0, 1 7 | while b < n: 8 | print(b, end=' ') 9 | a, b = b, a + b 10 | print() 11 | 12 | 13 | # 输出斐波那契数组 14 | def fib2(n): 15 | result = [] 16 | a, b = 0, 1 17 | while b < n: 18 | result.append(b) 19 | a, b = b, a + b 20 | return result 21 | 22 | 23 | if __name__ == '__main__': 24 | """ 25 | sys.argv 是从外部获取参数,不要盲目运行,否则会报越界异常 26 | 27 | sys.argv[0] 是文件本身,是没有任何输出的 28 | 29 | sys.argv[1] 则输出数据本身 30 | 31 | 本例用法: 32 | 1. 打开命令行并切换到本目录下 33 | 2. python test05_fib.py 数据(如 python test05_fib.py 123) 34 | 3. 得到fib数列 1 1 2 3 5 8 13 21 34 55 89 35 | """ 36 | num = int(sys.argv[1]) 37 | if num >= 50: 38 | fib(num) 39 | else: 40 | print(fib2(num)) -------------------------------------------------------------------------------- /base_demo/test06_look_04.py: -------------------------------------------------------------------------------- 1 | import urllib 2 | from urllib import request 3 | 4 | """ 5 | 这个是写重复了 6 | 7 | 本目录的test04 8 | commonlib: lib_urllib # 原生 9 | ex_lib: ex_lib_requests # 框架 10 | 还有其他的 11 | """ 12 | 13 | url = 'http://wthrcdn.etouch.cn/weather_mini?city=深圳' 14 | req = urllib.request.Request(url) 15 | ret = urllib.request.urlopen(req) 16 | data = ret.read() 17 | 18 | data = data.decode("utf-8") 19 | print(data, type(data)) 20 | -------------------------------------------------------------------------------- /base_demo/test07_input.py: -------------------------------------------------------------------------------- 1 | birth = 0 2 | temp = input('birth: ') 3 | 4 | 5 | def m_global(): 6 | global birth 7 | global temp 8 | while not temp.isdigit(): 9 | if not temp.isdigit(): 10 | birth = 0 11 | temp = input("抱歉,您的输入有误,请输入一个整数:") 12 | else: 13 | birth = int(temp) 14 | 15 | 16 | if __name__ == '__main__': 17 | m_global() 18 | if birth < 2000: 19 | print('00前') 20 | else: 21 | print('00后') 22 | -------------------------------------------------------------------------------- /base_demo/test08_work_is_fat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-15 15:42:56 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : $Id$ 7 | 8 | # bmi低于18.5:过轻 9 | # 18.5-25:正常 10 | # 25-28:过重 11 | # 28-32:肥胖 12 | # 高于32:严重肥胖 13 | 14 | height = 1.75 15 | weight = 80.5 16 | 17 | bmi = weight / (height ** 2) 18 | print(bmi) 19 | 20 | if bmi < 18.5: 21 | print("so light!") 22 | elif 18.5 <= bmi < 25: 23 | print("nice!") 24 | elif 25 <= bmi < 28: 25 | print("little heavy!") 26 | elif 28 <= bmi < 32: 27 | print("fat!") 28 | elif bmi > 32: 29 | print("so fat!!!") 30 | -------------------------------------------------------------------------------- /base_demo/test09_range.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-15 17:26:16 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : $Id$ 7 | 8 | sum = 0 9 | 10 | # range(101) 也可以 11 | for x in range(0, 101): 12 | sum += x 13 | 14 | print("for:%d" % sum) 15 | 16 | sum = 0 17 | n = 100 18 | while n > 0: 19 | sum += n 20 | n -= 1 21 | 22 | print("while:%d" % sum) 23 | 24 | L = ['Bart', 'Lisa', 'Adam'] 25 | for name in L: 26 | print("Hello", name) 27 | -------------------------------------------------------------------------------- /base_demo/test10_sum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-15 17:41:09 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : $Id$ 7 | 8 | PI = 3.1415926 9 | r = input("num:") 10 | 11 | S = PI * float(r) ** 2 # 乘方的优先级高于乘 12 | print("%.2f" % S) 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /base_demo/test11_hex.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # hex() 十六进制转换 3 | 4 | n1 = 255 5 | n2 = 1000 6 | 7 | print(hex(n1), "\n%s" % hex(n2)) 8 | -------------------------------------------------------------------------------- /base_demo/test12_math.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import math 3 | 4 | 5 | def my_abs(arg_name_is_x): 6 | arg_name_is_x = int(arg_name_is_x) 7 | if not isinstance(arg_name_is_x, (int, float)): 8 | raise TypeError("类型错误,请输入数字!") 9 | if arg_name_is_x > 0: 10 | print(arg_name_is_x) 11 | else: 12 | print(-arg_name_is_x) 13 | 14 | 15 | # 返回多个值(元组) 16 | # 参数为坐标,位移,角度 17 | def move(x, y, step, angle=0): 18 | nx = x + step * math.cos(angle) 19 | ny = y - step * math.sin(angle) 20 | return nx, ny 21 | 22 | 23 | is_stop = True 24 | 25 | if __name__ == '__main__': 26 | # 打印元组 27 | print(move(100, 100, 100, 90)) 28 | # abs测试 29 | x = input("absNum:") 30 | my_abs(x) 31 | while is_stop: 32 | stop_controller = input("isStop? \nYes:1 No:0\n") 33 | if int(stop_controller) == 1: 34 | is_stop = True 35 | x = input("absNum:") 36 | my_abs(x) 37 | elif int(stop_controller) == 0: 38 | is_stop = False 39 | else: 40 | stop_controller = input("you not type 0 or 1! \nYes:1 No:0\n") 41 | is_stop = True 42 | 43 | 44 | -------------------------------------------------------------------------------- /base_demo/test13_math_quadratic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-16 10:23:35 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : $Id$ 7 | 8 | # 请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程: 9 | 10 | # ax2 + bx + c = 0(a!=0)的两个解。 11 | import math 12 | 13 | 14 | def quadratic(a, b, c): 15 | for i in a, b, c: 16 | if not isinstance(i, (int, float)): 17 | raise TypeError('int or float') 18 | 19 | if a == 0: 20 | raise SyntaxError("error! a != 0") 21 | 22 | d = b ** 2 - 4 * a * c 23 | if d < 0: 24 | return print('error') 25 | elif d >= 0: 26 | x1 = (-b + math.sqrt(d)) / (2 * a) 27 | x2 = (-b - math.sqrt(d)) / (2 * a) 28 | return x1, x2 29 | 30 | 31 | if __name__ == '__main__': 32 | print(quadratic(2, 3, 1)) # => (-0.5, -1.0) 33 | print(quadratic(1, 3, -4)) # => (1.0, -4.0) 34 | -------------------------------------------------------------------------------- /base_demo/test14_args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-16 17:04:31 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : $Id$ 7 | 8 | 9 | def powers(x=0, n=2): # 默认参数 必须指向不变对象 10 | return x ** n 11 | 12 | 13 | def cola(*nums): # 可变参数 14 | sum = 0 15 | for num in nums: 16 | sum += num 17 | return sum 18 | 19 | 20 | def keywordargs(no, *name, **keyword): # 关键词参数 如果有可变参数,遵守可变参数原则 21 | # 如果要默认关键词,需要用*作为分隔符 keywordargs(no, *name, *, city='深圳') 22 | return "no:", no, "name:", name, "other:", keyword 23 | 24 | 25 | if __name__ == '__main__': 26 | print(powers(3, 5)) 27 | print(cola(1, 2, 3)) 28 | print(cola(1, 2, 3, 4)) 29 | print(cola(1, 2, 3, 4, 5)) 30 | print(keywordargs(23, "张三", "小张三", remark="张三小时候叫小张三", city="深圳", country="北京")) 31 | 32 | print(powers()) 33 | print(cola()) 34 | print(keywordargs(1)) 35 | -------------------------------------------------------------------------------- /base_demo/test15_work_product.py: -------------------------------------------------------------------------------- 1 | def product(*nums): 2 | if nums is None or len(nums) <= 0: 3 | raise TypeError("args not null!") 4 | product = 1 5 | for num in nums: 6 | product *= num 7 | return product 8 | 9 | 10 | if __name__ == '__main__': 11 | # 测试 12 | print('product(5) =', product(5)) 13 | print('product(5, 6) =', product(5, 6)) 14 | print('product(5, 6, 7) =', product(5, 6, 7)) 15 | print('product(5, 6, 7, 9) =', product(5, 6, 7, 9)) 16 | if product(5) != 5: 17 | print('测试失败!') 18 | elif product(5, 6) != 30: 19 | print('测试失败!') 20 | elif product(5, 6, 7) != 210: 21 | print('测试失败!') 22 | elif product(5, 6, 7, 9) != 1890: 23 | print('测试失败!') 24 | else: 25 | try: 26 | product() 27 | print('测试失败!') 28 | except TypeError: 29 | print('测试成功!') 30 | -------------------------------------------------------------------------------- /base_demo/test16_recursive.py: -------------------------------------------------------------------------------- 1 | # 递归阶乘 超过栈容易溢出 2 | def recursive(n): 3 | if n == 1: 4 | return 1 5 | return n * recursive(n - 1) 6 | 7 | 8 | # 尾递归 优化,末尾调用时函数调用前运算,可以始终调用一个栈,简直就是扯淡 9 | def optimize(n, product): 10 | if n == 1: 11 | return product 12 | return optimize(n - 1, n * product) 13 | 14 | 15 | # 循环测试 16 | def for_test(ns): 17 | temp = 1 18 | for n in range(1, ns+1): 19 | temp *= n 20 | return temp 21 | 22 | 23 | if __name__ == '__main__': 24 | print(recursive(100)) 25 | 26 | # print(optimize(500, 1000)) 27 | # print(optimize(4, 5)) 28 | # print(optimize(3, 20)) 29 | # print(optimize(2, 60)) 30 | # print(optimize(1, 120)) 31 | print(for_test(100)) 32 | -------------------------------------------------------------------------------- /base_demo/test17_trim.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-20 10:24:08 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : 1 7 | 8 | 9 | def trim(s): 10 | # 判断是否符合trim条件 11 | if len(s) == 0 or s[0] != ' ' and s[-1] != ' ': 12 | return s 13 | else: 14 | # 递归去空 15 | return trim(s[0] == ' ' and s[1:] or s[:-1]) 16 | 17 | 18 | # 测试: 19 | if __name__ == '__main__': 20 | if trim('hello ') != 'hello': 21 | print('测试失败!') 22 | elif trim(' hello') != 'hello': 23 | print('测试失败!') 24 | elif trim(' hello ') != 'hello': 25 | print('测试失败!') 26 | elif trim('') != '': 27 | print('测试失败!') 28 | elif trim(' ') != '': 29 | print('测试失败!') 30 | else: 31 | print('测试成功!') 32 | -------------------------------------------------------------------------------- /base_demo/test18_Iterable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-20 11:21:52 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # 迭代 8 | 9 | # 判断迭代 10 | from collections import Iterable 11 | 12 | 13 | d = {'a': 1, 'b': 2, 'c': 3} 14 | for key in d: 15 | print(key, d[key]) 16 | 17 | print("\n") 18 | for k, v in enumerate(d): 19 | print(k, v) 20 | 21 | print(isinstance(d, Iterable)) 22 | 23 | print(isinstance("123", Iterable)) 24 | 25 | print(isinstance(123, Iterable)) 26 | -------------------------------------------------------------------------------- /base_demo/test19_work_k_v.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-20 17:23:30 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | 8 | 9 | def test_d(d): 10 | for k, v in d.items(): 11 | return k, '=', v 12 | 13 | 14 | def test_s(L): 15 | L2 = [] 16 | for s in L: 17 | if isinstance(s, str): 18 | L2.append(s.lower()) 19 | return L2 20 | 21 | 22 | if __name__ == '__main__': 23 | # 测试: 24 | L1 = ['Hello', 'World', 18, 'Apple', None] 25 | L2 = test_s(L1) 26 | if L2 == ['hello', 'world', 'apple']: 27 | print('测试通过!') 28 | else: 29 | print('测试失败!') 30 | -------------------------------------------------------------------------------- /base_demo/test20_reduce.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-23 11:24:23 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | 8 | 9 | L = [1, 2, 3, 4, 5, 6, 7, 8, 9] 10 | 11 | 12 | def f(x): 13 | return x * x 14 | 15 | 16 | from functools import reduce 17 | 18 | 19 | def add(x, y): 20 | return x + y 21 | 22 | 23 | def add2(x, y): 24 | return x * 10 + y 25 | 26 | 27 | def char2num(s): 28 | return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, "6": 6, '7': 7, '8': 8, '9': 9}[s] 29 | 30 | 31 | def str2int(s): 32 | def add2(x, y): 33 | return x * 10 + y 34 | 35 | def char2num(s): 36 | return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, "6": 6, '7': 7, '8': 8, '9': 9}[s] 37 | # return reduce(lambda x, y: x * 10 + y, map(char2num, s)) 简化版 38 | return reduce(add2, map(char2num, s)) 39 | 40 | 41 | if __name__ == '__main__': 42 | print(list(map(f, L))) 43 | 44 | print(list(map(str, L))) 45 | 46 | print(sum([1, 3, 5, 7, 9])) 47 | 48 | print(reduce(add, [1, 3, 5, 7, 9])) 49 | print(reduce(add2, [1, 3, 5, 7, 9])) 50 | 51 | print(reduce(add2, map(char2num, '13579'))) 52 | print(str2int('13579')) 53 | -------------------------------------------------------------------------------- /base_demo/test21_filter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/24 0024 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | 8 | L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 9 | L2 = ['A', 'B', 'c', None, ' '] 10 | L3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] 11 | 12 | 13 | def is_odd(n): # 是否奇数 14 | return n % 2 == 1 15 | 16 | 17 | def not_empty(s): # 不为空 18 | return s and s.strip() 19 | 20 | 21 | def odd_iter(): # 奇数生成器 22 | n = 1 23 | while True: 24 | n += 2 25 | yield n 26 | 27 | 28 | def not_divisible(n): # 筛选函数 29 | return lambda x: x % n > 0 30 | 31 | 32 | def primes(): # 生成素数列表 33 | yield 2 34 | it = odd_iter() # 初始序列 35 | while True: 36 | n = next(it) # 返回序列的第一个数 37 | yield n 38 | it = filter(not_divisible(n), it) # 构造新序列 39 | 40 | 41 | if __name__ == '__main__': 42 | # print(list(filter(is_odd, L1))) # [1, 3, 5, 7, 9] 43 | # print(list(filter(not_empty, L2))) # ['A', 'B', 'c'] 44 | # 打印100以内的素数: 45 | for n in primes(): 46 | if n < 100: 47 | print(n) 48 | else: 49 | break 50 | -------------------------------------------------------------------------------- /base_demo/test22_sorted.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-24 14:13:06 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | 8 | L_num = [1, 0, -9, 22, -89] 9 | L_str = ['bob', 'about', 'Zoo', 'Credit'] 10 | 11 | # 假设我们用一组tuple表示学生名字和成绩: 12 | L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 13 | 14 | 15 | def by_name(t): 16 | return t[0] 17 | 18 | 19 | def by_score(t): 20 | return t[1] 21 | 22 | 23 | if __name__ == '__main__': 24 | # print("-" * 15, "对list排序", "-" * 15) 25 | # print(sorted(L_num)) 26 | # 27 | # print("-" * 15, "用key函数自定义排序", "-" * 15) 28 | # print(sorted(L_num, key=abs)) 29 | # 30 | # print("-" * 15, "默认str排序,按ASCII排序,Z>a", "-" * 15) 31 | # print(sorted(L_str)) 32 | # 33 | # print("-" * 15, "忽略大小写排序", "-" * 15) 34 | # print(sorted(L_str, key=str.lower)) 35 | # 36 | # print("-" * 15, "忽略大小写并反向排序", "-" * 15) 37 | # print(sorted(L_str, key=str.lower, reverse=True)) 38 | 39 | # print("-" * 50) 40 | print("-" * 15, "用sorted()对L分别按名字排序", "-" * 15) 41 | L2 = sorted(L, key=by_name) 42 | print(L2) 43 | print("-" * 15, "按成绩排序", "-" * 15) 44 | L2 = sorted(L, key=by_score) 45 | print(L2) 46 | -------------------------------------------------------------------------------- /base_demo/test23_return.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-27 18:48:55 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | 8 | 9 | def calc_sum(*args): 10 | x = 0 11 | for n in args: 12 | x = x + n 13 | return x 14 | 15 | 16 | def lazy_sum(*args): 17 | def in_sum(): 18 | x = 0 19 | for n in args: 20 | x = x + n 21 | return x 22 | return in_sum 23 | 24 | 25 | if __name__ == '__main__': 26 | f = calc_sum(1, 3, 5, 7, 9) 27 | print(f) 28 | 29 | f = lazy_sum(1, 3, 5, 7, 9) 30 | print(f) 31 | print(f()) 32 | -------------------------------------------------------------------------------- /base_demo/test24_lambda.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-28 14:16:26 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # #des: 匿名函数 8 | 9 | # 在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数: 10 | from typing import Iterator 11 | 12 | 13 | # l = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) 14 | 15 | 16 | # print(l) 17 | 18 | 19 | def build(x, y): 20 | return lambda: x * x + y * y 21 | 22 | 23 | def is_odd(n): 24 | return n % 2 == 1 25 | 26 | 27 | if __name__ == '__main__': 28 | # print(f) 29 | # print(f(2, 3)) 30 | L = list(filter(is_odd, range(1, 20))) 31 | print(L) 32 | L2 = list(filter(lambda n: n % 2, range(1, 20))) 33 | print(L2) 34 | -------------------------------------------------------------------------------- /base_demo/test25_decorate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-28 15:47:14 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | 8 | 9 | # 由于log()是一个decorator,返回一个函数, 10 | # 所以,原来的now()函数仍然存在, 11 | # 只是现在同名的now变量指向了新的函数, 12 | # 于是调用now()将执行新函数, 13 | # 即在log()函数中返回的wrapper()函数。 14 | 15 | # wrapper()函数的参数定义是(*args, **kw), 16 | # 因此,wrapper()函数可以接受任意参数的调用。 17 | # 在wrapper()函数内,首先打印日志,再紧接着调用原始函数。 18 | 19 | # 初阶log函数 20 | def log(func): 21 | def wrapper(*args, **kw): 22 | print('call %s():' % func.__name__) 23 | return func(*args, **kw) 24 | return wrapper 25 | 26 | 27 | # 高阶log函数 28 | def log2(text): 29 | def decorate(func): 30 | def wrapper(*args, **kw): 31 | print("%s %s:" % (text, func.__name__)) 32 | return func(*args, **kw) 33 | return wrapper 34 | return decorate 35 | 36 | 37 | @log 38 | @log2('execute') 39 | def now(): 40 | print('2017-11-28') 41 | 42 | 43 | if __name__ == '__main__': 44 | now() 45 | -------------------------------------------------------------------------------- /base_demo/test26_partial.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/28 0028 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | 8 | from functools import partial 9 | 10 | print('---------无关键词参数--------') 11 | 12 | 13 | def mod(n, m): 14 | return n % m 15 | 16 | 17 | mod_by_100 = partial(mod, 100) 18 | print(mod(100, 7)) # 2 19 | print(mod_by_100(7)) # 2 20 | 21 | print('---------进制转换--------') 22 | 23 | str2int = lambda x, base=2: int(x, base) 24 | print(str2int('10000')) 25 | print(str2int('12345', 16)) 26 | print(str2int('123456', base=8)) 27 | 28 | bin2dec = partial(int, base=2) 29 | print(bin2dec('0b10001')) # 17 30 | print(bin2dec('10001')) # 17 31 | 32 | hex2dec = partial(int, base=16) 33 | print(hex2dec('0x67')) # 103 34 | print(hex2dec('67')) # 103 35 | 36 | 37 | -------------------------------------------------------------------------------- /base_demo/test27_use_modules.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-29 11:57:01 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # @des : 使用模块 8 | 9 | import sys 10 | 11 | __author__ = "TaoYuan" 12 | 13 | 14 | def test(): 15 | args = sys.argv 16 | if len(args) == 1: 17 | print("Hello {0}".format(args[0])) 18 | elif len(args) == 2: 19 | print("Hello {0}".format(args[1])) 20 | else: 21 | print("args too much!") 22 | 23 | 24 | def _private_1(name): 25 | return "Hello {0}".format(name) 26 | 27 | 28 | def _private_2(name): 29 | return 'Hi {0}'.format(name) 30 | 31 | 32 | def public_one(name): 33 | if len(name) > 3: 34 | return _private_1(name) 35 | else: 36 | return _private_2(name) 37 | 38 | 39 | if __name__ == '__main__': 40 | test() 41 | print('----------') 42 | print(public_one("123")) 43 | print(public_one("123456")) 44 | -------------------------------------------------------------------------------- /base_demo/test28_path.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/7 0007. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import os 8 | import sys 9 | 10 | print('-----------获取本文件地址----------') 11 | print(os.path.realpath(__file__)) 12 | print(os.path.abspath(__file__)) # 推荐方法 13 | 14 | # 注意这两个方法的分隔符,不推荐使用 15 | print(__file__) 16 | print(sys.argv[0]) 17 | 18 | 19 | print('-----------获取本文件所在目录----------') 20 | print(os.path.dirname(os.path.realpath(__file__))) 21 | print(os.path.split(os.path.realpath(__file__))[0]) 22 | print(os.getcwd()) 23 | print(sys.path[0]) 24 | 25 | print('-----------获取上级目录----------') 26 | print(os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) 27 | print(os.path.abspath(os.path.dirname(os.getcwd()))) 28 | print(os.path.abspath(os.path.join(os.getcwd(), ".."))) 29 | 30 | print('-----------获取上上级目录---------') 31 | print(os.path.abspath(os.path.join(os.getcwd(), "../.."))) 32 | 33 | print('-----------本级目录下新建目录---------') 34 | print(os.path.abspath(os.path.join(os.getcwd(), "img"))) 35 | 36 | print('-----------本盘符下新建目录---------') 37 | print(os.path.abspath(os.path.join(os.getcwd(), "/img"))) 38 | -------------------------------------------------------------------------------- /base_demo/test29_serialize.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/8 0008. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 序列化 8 | 9 | import pickle 10 | 11 | # write serialize(bytes) in file 12 | # d = dict(name="Bob", age=20, score=88) 13 | # print(pickle.dumps(d)) # b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x03\x00\x00\x00Bobq\x02X\x03\x00\x00\x00ageq\x03K\x14X\x05\x00\x00\x00scoreq\x04KXu.' 14 | # 15 | # f = open("dump.txt", "wb") 16 | # pickle.dump(d, f) 17 | # f.close() 18 | 19 | # read serialize 20 | a = open("dump.txt", "rb") 21 | b = pickle.load(a) 22 | a.close() 23 | print(b) # {'name': 'Bob', 'age': 20, 'score': 88} 24 | -------------------------------------------------------------------------------- /base_demo/test30_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/8 0008. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | import json 9 | 10 | """ 11 | standard json 12 | """ 13 | 14 | # create json 15 | # d = dict(name="Bob", age=20, score=88) 16 | # print(json.dumps(d)) # {"name": "Bob", "age": 20, "score": 88} 17 | 18 | # load json 19 | # json_str = '{"name": "Bob", "age": 20, "score": 88}' 20 | # print(json.loads(json_str)) # {'name': 'Bob', 'age': 20, 'score': 88} 21 | 22 | 23 | """ 24 | advanced usage 25 | """ 26 | 27 | 28 | class Student(object): 29 | """docstring for Student""" 30 | 31 | def __init__(self, name, age, score): 32 | super(Student, self).__init__() 33 | self.name = name 34 | self.age = age 35 | self.score = score 36 | 37 | 38 | def cls2dict(in_cls): 39 | return { 40 | "name": in_cls.name, 41 | "age": in_cls.age, 42 | "score": in_cls.score 43 | } 44 | 45 | 46 | def dict2cls(in_dict): 47 | return Student(in_dict["name"], in_dict["age"], in_dict["score"]) 48 | 49 | 50 | # s = Student("Bob", 20, 88) 51 | # print(json.dumps(s, default=cls2dict)) # {"name": "Bob", "age": 20, "score": 88} 52 | json_str = '{"age": 20, "score": 88, "name": "Bob"}' 53 | print(json.loads(json_str, object_hook=dict2cls)) # <__main__.Student object at 0x00000000028F46D8> 54 | 55 | 56 | -------------------------------------------------------------------------------- /base_demo/test31_regex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/12 0012. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # Regular Expression 8 | import re 9 | 10 | # string 11 | s1 = "ABC\\-001" # python lang support Escape Sequence 12 | s2 = r"ABC\\-001" # so, recommend use r'' 13 | regex_01 = r"^\d{3}\-\d{3,9}$" 14 | 15 | # project commonly used method 16 | if re.match(r"your regex", "user input content"): 17 | print("ok") 18 | else: 19 | print("error") 20 | 21 | # split string 22 | s3 = "a b c d e" 23 | s4 = "a,b,c ,d e" 24 | regex_02 = r"\s+" 25 | regex_03 = r"[\s\,]+" 26 | 27 | # grouping 28 | s5 = "029-1234567" 29 | s6 = "0755-123456" 30 | regex_group1 = r"^(\d{3})-(\d{3,8})$" # 3个数字,3-8个数字 31 | regex_group2 = r"^(\d{3,4})-(\d{6})$" # 3-4个数字,6个数字 32 | 33 | if __name__ == '__main__': 34 | # string 35 | print(s1) # ABC\-001 36 | print(s2) # ABC\\-001 37 | print(re.match(regex_01, "029-123456")) # <_sre.SRE_Match object; span=(0, 10), match='029-123456'> 38 | print(re.match(regex_01, "0755-123456")) # None 39 | print("-" * 20) 40 | # split string 41 | print(s3.split(" ")) # nomal 42 | print(s4.split(",")) # nomal 43 | print(re.split(regex_02, s3)) # regex 44 | print(re.split(regex_03, s4)) # regex 45 | print("-" * 20) 46 | # grouping 47 | # group(0)永远是原始字符串 48 | m1 = re.match(regex_group1, s5) # 这个限定了第一组只能用3个数字,否则报错 49 | print(m1.group(0)) 50 | print(m1.group(1)) 51 | print(m1.group(2)) 52 | m2 = re.match(regex_group2, s6) # 这个限定了第二组只能是6位数字,否则报错 53 | print(m2.group(0)) 54 | print(m2.group(1)) 55 | print(m2.group(2)) 56 | -------------------------------------------------------------------------------- /commonlib/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/13 0013. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # # 为了防止和内置模块重名导致异常,建议前缀 -------------------------------------------------------------------------------- /commonlib/code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/commonlib/code.png -------------------------------------------------------------------------------- /commonlib/lib_base64.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/14 0014. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # base64 8 | import base64 9 | 10 | s = b"i\xb7\x1d\xfb\xef\xff" 11 | # def test(): 12 | # s0 = b"Aladdin:open sesame" 13 | # print(repr(s0)) 14 | # s1 = encodebytes(s0) 15 | # print(repr(s1)) 16 | # s2 = decodebytes(s1) 17 | # print(repr(s2)) 18 | # assert s0 == s2 19 | base64.test() 20 | # b'Aladdin:open sesame' 21 | # b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n' 22 | # b'Aladdin:open sesame' 23 | print("-----------------------") 24 | # url encode 25 | url_base64 = base64.urlsafe_b64encode(s) 26 | print(url_base64) 27 | print(base64.urlsafe_b64decode(url_base64)) 28 | print("-----------------------") 29 | # normal 30 | normal_base64 = base64.b64encode(s) 31 | print(normal_base64) 32 | print(base64.b64decode(normal_base64)) 33 | print("-----------------------") 34 | # other 35 | print(base64.encodebytes(s)) # encodebytes 对string进行base64编码 36 | base64.decodebytes(b'abcd++//\n') # decodebytes 解码一组base64数据 37 | print(base64.encodestring(s)) # Legacy alias of encodebytes() 38 | base64.decodestring(b'abcd++//\n') # Legacy alias of decodebytes() 39 | print(base64.standard_b64encode(s)) # 使用标准Base64字母表对字节进行编码,返回byteArray 40 | base64.standard_b64encode(b'abcd++//') # 使用标准Base64字母表对字节进行编码,返回byteArray 41 | -------------------------------------------------------------------------------- /commonlib/lib_collections.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/14 0014. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # collections是Python内建的一个集合模块,提供了许多有用的集合类。 8 | from collections import namedtuple, deque, defaultdict, OrderedDict, Counter 9 | 10 | # nametuple(tuple) 11 | point = namedtuple("point", ['x', 'y']) 12 | p = point(1, 2) 13 | print(p.x, p.y) 14 | 15 | # nametuple 看名字应该也是属于tuple的子类 16 | print(isinstance(p, point)) 17 | print(isinstance(p, tuple)) 18 | 19 | print("-------------------") 20 | # deque 一种类似列表的序列,用于在其端点附近访问数据 21 | # 使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了 22 | # 因为list是线性存储,数据量大的时候,插入和删除效率很低。 23 | # deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈 24 | q = deque(['a', 'b', 'c']) 25 | q.append('x') # 从右边添加一个元素 26 | q.appendleft('y') # 从左边添加一个元素 27 | print(q) # deque(['y', 'a', 'b', 'c', 'x']) 28 | # deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素。 29 | print("-------------------") 30 | 31 | # defaultdict 32 | # 使用dict时,如果引用的Key不存在,就会抛出KeyError 33 | # 如果希望key不存在时,返回一个默认值,就可以用defaultdict 34 | # 除了在Key不存在时返回默认值,defaultdict的其他行为跟dict是完全一样的。 35 | dd = defaultdict(lambda: "no value") 36 | dd['key1'] = "abc" 37 | print(dd['key1']) # abc 38 | print(dd['key2']) # no value 39 | 40 | print("-------------------") 41 | # OrderedDict 42 | # 使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。 43 | # 如果要保持Key的顺序,可以用OrderedDict 44 | # Dictionary that remembers insertion order记住插入顺序的字典 45 | d = dict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) 46 | print(d) # {'a': 1, 'b': 2, 'c': 3} 47 | od = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) 48 | print(od) 49 | 50 | 51 | # OrderedDict的Key会按照插入的顺序排列,不是Key本身排序 52 | # OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key 53 | class FIFO(OrderedDict): 54 | """docstring for FIFO:last update ordered dict""" 55 | def __init__(self, capacity): 56 | super(FIFO, self).__init__() 57 | self._capacity = capacity 58 | 59 | def __setitem__(self, key, value): 60 | containKey = 1 if key in self else 0 61 | if len(self) - containKey >= self._capacity: 62 | last = self.popitem(last=False) 63 | print("remove:", last) 64 | if containKey: 65 | del self[key] 66 | print("set:", (key, value)) 67 | else: 68 | print("add:", (key, value)) 69 | OrderedDict.__setitem__(self, key, value) 70 | 71 | 72 | print("-------------------") 73 | # counter 计数器 74 | # Counter实际上也是dict的一个子类,下面的代码中重复的都去掉了 75 | c = Counter() 76 | for ch in "programming": 77 | c[ch] += 1 78 | print(c) # Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1}) 79 | -------------------------------------------------------------------------------- /commonlib/lib_contextlib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/17. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | # try: 9 | # f = open("../2.txt") 10 | # f.read() 11 | # except Exception as e: 12 | # raise FileNotFoundError("file not fpund!") 13 | # finally: 14 | # if f: 15 | # f.close() 16 | 17 | # with open("../2.txt", "r") as f: 18 | # f.read() 19 | 20 | 21 | # 并不是只有open()函数返回的fp对象才能使用with语句。 22 | # 任何对象,只要正确实现了上下文管理,就可以用于with语句。 23 | # 实现上下文管理是通过__enter__和__exit__这两个方法实现的。 24 | # class Query(object): 25 | # """docstring for Query""" 26 | 27 | # def __init__(self, name): 28 | # self.name = name 29 | 30 | # def __enter__(self): 31 | # print("begin..") 32 | # return self 33 | 34 | # def __exit__(self, exc_type, exc_value, traceback): 35 | # if exc_type: 36 | # print("Error") 37 | # else: 38 | # print("End") 39 | # def query(self): 40 | # print("Query info about %s..." % self.name) 41 | 42 | # with Query("Bob") as q: 43 | # q.query() 44 | 45 | # 编写__enter__和__exit__仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下 46 | from contextlib import contextmanager 47 | 48 | 49 | # class Query(object): 50 | # """docstring for Query""" 51 | # def __init__(self, name): 52 | # self.name = name 53 | 54 | # def query(self): 55 | # print("Query info about %s..." % self.name) 56 | 57 | 58 | # @contextmanager 59 | # def create_query(name): 60 | # print("begin...") 61 | # q = Query(name) 62 | # yield q 63 | # print("end") 64 | 65 | # # @contextmanager这个decorator接受一个generator,用yield语句把with ... as var把变量输出出去 66 | # # 然后,with语句就可以正常地工作了 67 | # with create_query("Bob") as q: 68 | # q.query() 69 | 70 | 71 | # 很多时候,我们希望在某段代码执行前后自动执行特定代码,也可以用@contextmanager实现。 72 | @contextmanager 73 | def tag(name): 74 | print("<%s>" % name) 75 | yield 76 | print("<%s>" % name) 77 | 78 | 79 | with tag("h1"): 80 | print("hello") 81 | print("world!") 82 | 83 | # 代码的执行顺序是: 84 | 85 | # 1. with语句首先执行yield之前的语句,因此打印出

; 86 | # 2. yield调用会执行with语句内部的所有语句,因此打印出hello和world; 87 | # 3. 最后执行yield之后的语句,打印出

。 88 | 89 | # closing 90 | from contextlib import contextmanager, closing 91 | from urllib.request import urlopen 92 | 93 | with closing(urlopen('https://www.python.org')) as page: 94 | for line in page: 95 | print(line) 96 | 97 | 98 | # closing也是一个经过@contextmanager装饰的generator,这个generator编写起来其实非常简单 99 | @contextmanager 100 | def my_closing(thing): 101 | try: 102 | yield thing 103 | finally: 104 | thing.close() 105 | 106 | # 它的作用就是把任意对象变为上下文对象,并支持with语句。 107 | # @contextlib还有一些其他decorator,便于我们编写更简洁的代码。 108 | -------------------------------------------------------------------------------- /commonlib/lib_datetime.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/13 0013. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # datetime是Python处理日期和时间的标准库。 8 | from datetime import datetime, timedelta, timezone 9 | 10 | print("-" * 10, "get current time", "-" * 10) 11 | current_time = datetime.now() # 获取当前datetime 12 | print(current_time) 13 | print(type(current_time)) 14 | # 2017-12-13 09:28:48.800766 15 | # 16 | 17 | 18 | print("\r\n") 19 | print("-" * 10, "datetime to timestamp", "-" * 10) 20 | # (self, year, month, day, hour, minute, second, microsecond,tzinfo: Optional[tzinfo] = ...) 21 | st = datetime(2017, 12, 13, 12, 0, 0) # 用指定日期时间创建datetime 22 | print(st.timestamp()) # 把datetime 转换为timestamp 23 | # 1513136723.0 24 | 25 | 26 | print("\r\n") 27 | print("-" * 10, "date format", "-" * 10) 28 | print(datetime.fromtimestamp(1513136723)) # 本地时间 29 | print(datetime.utcfromtimestamp(1513136723)) # UTC时间 30 | print(datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')) # string to datetime 31 | print(current_time.strftime("%Y-%m-%d %H:%M:%S")) # datetime to string,like java 32 | 33 | print("\r\n") 34 | print("-" * 10, "计算时间(datetime加减)", "-" * 10) 35 | print("now:", current_time) 36 | print("one day off:", current_time + timedelta(1)) 37 | print("one days ago:", current_time - timedelta(days=1, hours=1)) 38 | 39 | print("\r\n") 40 | print("-" * 10, "本地时间转换为UTC时间", "-" * 10) 41 | tz_utc_8 = timezone(timedelta(hours=8)) # 创建东八区时区 42 | print(current_time) 43 | print(current_time.replace(tzinfo=tz_utc_8)) # 强制设置为UTC+8:00 44 | # 2017-12-13 19:59:06.630822 45 | # 2017-12-13 19:59:06.630822+08:00 46 | -------------------------------------------------------------------------------- /commonlib/lib_hashlib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等 8 | import hashlib 9 | 10 | s = b"Nobody inspects the spammish repetition" 11 | m = hashlib.md5() 12 | m.update(b"Nobody inspects ") # b'>\xf7)\xcc\xf0\xccV\x07\x9c\xa5F\xd5\x80\x83\xdc\x12' 13 | m.update(b"the spammish repetition") # b'>\xf7)\xcc\xf0\xccV\x07\x9c\xa5F\xd5\x80\x83\xdc\x12' 14 | # 多次调用,update会累加参数进行运算 15 | # m.update(s) # bb649c83dd1ea5c9d9dec9a18df0ffe9 16 | # print(m.digest()) # b'%\x8d3\xf9,:k\xe0?\xbb0+\xc4K\x94S' 17 | print(m.hexdigest()) 18 | 19 | print("--------------") 20 | # 常用 简写 21 | # my_md5 = hashlib.md5() 22 | # my_md5.update(s) 23 | # my_md5.hexdigest() 24 | print(hashlib.md5(s).hexdigest()) 25 | print(hashlib.sha1(s).hexdigest()) 26 | print(hashlib.sha256(s).hexdigest()) 27 | print(hashlib.sha512(s).hexdigest()) 28 | 29 | # bb649c83dd1ea5c9d9dec9a18df0ffe9 30 | # 531b07a0f5b66477a21742d2827176264f4bbfe2 31 | # 031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406 32 | # d0f4c14c48ad4837905ea7520cc4af700f6433ce0985e6bb87b6b4617cb944abf814bd53964ddbf55b41e5812b3afe90890c0a4db75cb04367e139fd62eab2e1 33 | 34 | 35 | -------------------------------------------------------------------------------- /commonlib/lib_hmac.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import hmac 8 | 9 | message = b"hello" 10 | key = b"secret" 11 | h = hmac.new(key, message, digestmod="MD5") 12 | print(h.hexdigest()) # bade63863c61ed0b3165806ecd6acefc 13 | -------------------------------------------------------------------------------- /commonlib/lib_htmlparse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/17. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # Python提供了HTMLParser来非常方便地解析HTML 8 | from html.parser import HTMLParser # 查找标记和其他标记和调用处理程序函数 9 | from html.entities import name2codepoint # 将HTML实体名称映射到Unicode代码点 10 | 11 | """ 12 | 利用HTMLParser,可以把网页中的文本、图像等解析出来。 13 | 14 | 15 | feed()方法可以多次调用,也就是不一定一次把整个HTML字符串都塞进去,可以一部分一部分塞进去。 16 | 特殊字符有两种,一种是英文表示的 ,一种是数字表示的Ӓ,这两种字符都可以通过Parser解析出来。 17 | """ 18 | 19 | 20 | class MyHTMLParse(HTMLParser): 21 | """docstring for MyHTMLParse""" 22 | 23 | def handle_starttag(self, tag, attrs): 24 | print("<{}>".format(tag)) 25 | 26 | def handle_endtag(self, tag): 27 | print("<{}>".format(tag)) 28 | 29 | def handle_startendtag(self, tag, attrs): 30 | print("<{}>".format(tag)) 31 | 32 | def handle_data(self, data): 33 | print(data) 34 | 35 | def handle_comment(self, data): 36 | print("".format(data)) 37 | 38 | def handle_entityref(self, name): 39 | print("&{};".format(name)) 40 | 41 | def handle_charref(self, name): 42 | print("&#{};".format(name)) 43 | 44 | 45 | parser = MyHTMLParse() 46 | parser.feed(""" 47 | 48 | 49 | 50 | 51 |

52 | Some 53 | html 54 | html tutorial...
55 | end 56 |

57 | 58 | 59 | """) 60 | -------------------------------------------------------------------------------- /commonlib/lib_itertools.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数 8 | import itertools 9 | 10 | # count()会创建一个无限的迭代器 11 | natuals = itertools.count(1) 12 | for n in natuals: 13 | print(n) 14 | 15 | # cycle()会把传入的一个序列无限重复下去 16 | # cs = itertools.cycle("ABC") 17 | # for c in cs: 18 | # print(c) 19 | 20 | # repeat()负责把一个元素无限重复下去,arg2限定次数 21 | # ns = itertools.repeat("ABC", 3) 22 | # for n in ns: 23 | # print(n) 24 | 25 | # takewhile()函数根据条件判断来截取出一个有限的序列 26 | # natuals = itertools.count(1) 27 | # ns = itertools.takewhile(lambda x: x <= 10, natuals) 28 | # print(list(ns)) 29 | 30 | # chain()可以把一组迭代对象串联起来,形成一个更大的迭代器 31 | # for c in itertools.chain("ABC", "XYZ"): 32 | # print(c) 33 | 34 | # groupby()把迭代器中相邻的重复元素挑出来放在一起 35 | # for key, group in itertools.groupby("ABBASID"): 36 | # print(key, list(group)) 37 | # # A ['A', 'a', 'a'] 38 | # # B ['B', 'B', 'b'] 39 | # # C ['c', 'C'] 40 | # # A ['A', 'A', 'a'] -------------------------------------------------------------------------------- /commonlib/lib_struct.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/14 0014. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 学过C/C++的人应该都知道结构体,python里没有 8 | # python中b'str'可以表示字节,所以,字节数组 = 二进制str,但是很麻烦 9 | # 幸好有struct这个模块,pack函数把任意数据类型变成bytes 10 | # https://docs.python.org/3/library/struct.html#format-characters 11 | import base64 12 | import struct 13 | 14 | # pack的第一个参数是处理指令 15 | # >I: >表示字节顺序是big-endian,也就是网络序,I表示4字节无符号整数。 16 | print(struct.pack(">I", 10240099)) # b'\x00\x9c@c' 17 | # 后面的参数个数要和处理指令一致1024 0099 18 | # print(base64.encodebytes(b'\x00\x9c@c')) # b'AJxAYw==\n' 19 | # unpack把bytes变成相应的数据类型: 20 | print(struct.unpack(">IH", b'\xf0\xf0\xf0\xf0\x80\x80')) # (4042322160, 32896) 21 | # I:4字节无符号整数 H:2字节无符号整数 22 | print("--------------------------") 23 | s = b'\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00' 24 | # BMP格式采用小端方式存储数据,文件头的结构按顺序如下 25 | # 两个字节:'BM'表示Windows位图,'BA'表示OS/2位图; 26 | # 一个4字节整数:表示位图大小; 27 | # 一个4字节整数:保留位,始终为0; 28 | # 一个4字节整数:实际图像的偏移量; 29 | # 一个4字节整数:Header的字节数; 30 | # 一个4字节整数:图像宽度; 31 | # 一个4字节整数:图像高度; 32 | # 一个2字节整数:始终为1; 33 | # 一个2字节整数:颜色数。 34 | print(struct.unpack(" 92 | name: Bob 93 | 94 | ORM就是把数据库表的行与相应的对象建立关联,互相转换 95 | 96 | 由于关系数据库的多个表还可以用外键实现一对多、多对多等关联 97 | 相应地,ORM框架也可以提供两个对象之间的一对多、多对多等功能。 98 | 99 | 例如,如果一个User拥有多个Book,就可以定义一对多关系如下: 100 | """ 101 | 102 | 103 | # class User(Base): 104 | # __tablename__ = 'user1' 105 | # 106 | # id = Column(String(20), primary_key=True) 107 | # name = Column(String(20)) 108 | # # 一对多: 109 | # books = relationship('Book') 110 | # 111 | # 112 | # class Book(Base): 113 | # __tablename__ = 'book' 114 | # 115 | # id = Column(String(20), primary_key=True) 116 | # name = Column(String(20)) 117 | # # “多”的一方的book表是通过外键关联到user表的: 118 | # user_id = Column(String(20), ForeignKey('user.id')) 119 | 120 | # 当我们查询一个User对象时,该对象的books属性将返回一个包含若干个Book对象的list -------------------------------------------------------------------------------- /db/db_sqlite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/20 0020. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | SQLite是一种嵌入式数据库,它的数据库就是一个文件 9 | iOS和Android的App中都可以集成 10 | 11 | Python就内置SQLite3 12 | 13 | Python定义了一套操作数据库的API接口 14 | 任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可 15 | 16 | SQLite的驱动内置在Python标准库中 17 | 18 | 使用Cursor对象执行insert,update,delete语句时,执行结果由rowcount返回影响的行数 19 | 20 | 使用Cursor对象执行select语句时,通过featchall()可以拿到结果集。 21 | 结果集是一个list,每个元素都是一个tuple,对应一行记录。 22 | ? 表示占位符,需要和参数对应 23 | cursor.execute('select * from user where name=? and pwd=?', ('abc', 'password')) 24 | """ 25 | 26 | # 导入驱动 27 | import sqlite3 28 | 29 | # 连接数据库,不存在则自动创建 30 | conn = sqlite3.connect("test.db") 31 | # 创建一个游标 32 | cursor = conn.cursor() 33 | # 创建user表 34 | cursor.execute("CREATE TABLE user (id VARCHAR(20) PRIMARY KEY, name TEXT)") 35 | # 添加一条记录 36 | cursor.execute("INSERT INTO user (id, name) VALUES('1', 'TaoYuan')") 37 | # 获取插入行数 38 | print(cursor.rowcount) 39 | 40 | 41 | # # 查询 42 | # cursor.execute("select * from user") 43 | # # 获取查询结果 44 | # values = cursor.fetchall() 45 | # print(values) # [('1', 'Taoyuan')] 46 | 47 | 48 | # 关闭游标 49 | cursor.close() 50 | # 提交事务 51 | conn.commit() 52 | # 关闭连接 53 | conn.close() 54 | -------------------------------------------------------------------------------- /django/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/1/16 0016. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways -------------------------------------------------------------------------------- /django/django_inner_fields.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/1/16 0016. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | 7 | """ 8 | 参考http://www.liujiangblog.com/course/django/95 9 | 本文只是记录Django中数据库常用字段类型 10 | 11 | from django.db import models 12 | class MyModel(models.Model): 13 | user_name = models.CharField(max_length=30) 14 | is_reg = models.BooleanField() 15 | user_age = model.IntegerField() 16 | ... 17 | """ 18 | 19 | 20 | 21 | 22 | # 常用 23 | 24 | 25 | """ 26 | 布尔值类型。默认值是None。 27 | 在HTML表单中体现为CheckboxInput标签。 28 | 如果要接收null值,请使用NullBooleanField。 29 | """ 30 | BooleanField 31 | 32 | 33 | """ 34 | 字符串类型 35 | 必须接收一个max_length参数,表示字符串长度不能超过该值 36 | 默认的表单标签是input text 37 | """ 38 | CharField 39 | 40 | 41 | """ 42 | 日期类型 datetime.date实例 43 | class DateField(auto_now=False, auto_now_add=False, **options) 44 | 45 | auto_now:每当对象被保存时将字段设为当前日期,常用于保存最后修改时间。 46 | auto_now_add:每当对象被创建时,设为当前日期,常用于保存创建日期(不可修改)。 47 | 48 | 如需具备修改属性,添加默认参数即可 49 | pub_time = models.DateField(auto_now_add=True) 50 | 51 | DateTimeField比DateField 多了时分秒,其他一样 52 | TimeField 只负责时分秒,其他一样 53 | """ 54 | DateField 55 | DateTimeField 56 | TimeField 57 | 58 | 59 | """ 60 | 固定精度的十进制小数。 61 | 62 | max_digits:最大的位数,必须大于或等于小数点位数 。 63 | decimal_places:小数点位数,精度。 64 | max_digits包含decimal_places的位数,如999.99 65 | max_digits确定总位数,decimal_places确定小数点后位数 66 | 67 | models.DecimalField(..., max_digits=5, decimal_places=2) 68 | """ 69 | DecimalField 70 | 71 | 72 | """ 73 | 上传文件类型 74 | class FileField(upload_to=None, max_length=100, **options) 75 | 默认情况下,该字段在HTML中表现为一个ClearableFileInput标签 76 | 在数据库内,我们实际保存的是一个字符串类型,默认最大长度100,可以通过max_length参数自定义。 77 | 真实的文件是保存在服务器的文件系统内的。 78 | 79 | upload_to用于设置上传地址的目录和文件名 80 | # 文件被传至`MEDIA_ROOT/uploads`目录,MEDIA_ROOT由你在settings文件中设置 81 | upload = models.FileField(upload_to='uploads/') 82 | # 被传到`MEDIA_ROOT/uploads/2015/01/30`目录,增加了一个时间划分 83 | upload = models.FileField(upload_to='uploads/%Y/%m/%d/') 84 | # 增加回调 85 | # user_directory_path这种回调函数,必须接收两个参数,然后返回一个Unix风格的路径字符串。 86 | # 参数instace代表一个定义了FileField的模型的实例,说白了就是当前数据记录。 87 | # filename是原本的文件名。 88 | def user_directory_path(instance, filename): 89 | #文件上传到MEDIA_ROOT/user_/目录中 90 | return 'user_{0}/{1}'.format(instance.user.id, filename) 91 | 92 | class MyModel(models.Model): 93 | upload = models.FileField(upload_to=user_directory_path) 94 | """ 95 | FileField 96 | 97 | 98 | """ 99 | 图像类型 100 | 使用Django的ImageField需要提前安装pillow模块 101 | pip install pillow 102 | class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)[source] 103 | 用于保存图像文件的字段。其基本用法和特性与FileField一样,只不过多了两个属性height和width。 104 | height_field参数:保存有图片高度信息的模型字段名。 105 | width_field参数:保存有图片宽度信息的模型字段名。 106 | 107 | 使用FileField或者ImageField字段的步骤: 108 | 109 | 1. 在settings文件中,配置MEDIA_ROOT,作为你上传文件在服务器中的基本路径(这些文件不会被储存在数据库中) 110 | 2. 再配置个MEDIA_URL,作为公用URL,指向上传文件的基本路径。请确保Web服务器的用户账号对该目录具有写的权限。 111 | 3. 添加FileField或者ImageField字段到你的模型中,定义好upload_to参数,文件最终会放在MEDIA_ROOT目录的“upload_to”子目录中。 112 | 4. 所有真正被保存在数据库中的,只是指向你上传文件路径的字符串而已。可以通过url属性,在Django的模板中方便的访问这些文件。 113 | 5. 假设你有一个ImageField字段,名叫mug_shot,那么在Django模板的HTML文件中,可以使用{{ object.mug_shot.url }}来获取该文件。 114 | 6. 其中的object用你具体的对象名称代替。 115 | 7. 可以通过name和size属性,获取文件的名称和大小信息。 116 | """ 117 | ImageField 118 | 119 | 120 | """ 121 | 一个自动增加的整数类型字段。 122 | 通常你不需要自己编写它,Django会自动帮你添加字段 123 | 124 | Exemple: 125 | id = models.AutoField(primary_key=True) 126 | 这是一个自增字段,从1开始计数。 127 | 如需设置主键,则需设置primary_key=True。 128 | 129 | Django在一个模型中只允许有一个自增字段 130 | 且必须为主键! 131 | """ 132 | AutoField 133 | 134 | 135 | """ 136 | 整数类型 137 | 取值范围-2147483648到2147483647 138 | """ 139 | IntegerField 140 | 141 | 142 | """ 143 | 浮点数类型 144 | """ 145 | FloatField 146 | 147 | 148 | """ 149 | 大量文本内容,在HTML中表现为Textarea标签 150 | 可以不设置max_length,如果设置了,还不如用CharField 151 | """ 152 | TextField 153 | 154 | 155 | """ 156 | 用于保存通用唯一识别码(Universally Unique Identifier)的字段。 157 | 在PostgreSQL数据库中保存为uuid类型,其它数据库中为char(32)。 158 | 很多公司用作自增主键, 是自增主键的最佳替代品 159 | import uuid # Python的内置模块 160 | from django.db import models 161 | 162 | class MyUUIDModel(models.Model): 163 | id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 164 | """ 165 | UUIDField 166 | 167 | 168 | # 验证类常用 169 | 170 | """ 171 | IP类型 172 | class GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)[source] 173 | 参数protocol默认值为‘both’,可选‘IPv4’或者‘IPv6’ 174 | """ 175 | GenericIPAddressField 176 | 177 | 178 | """ 179 | 邮箱类型,默认max_length最大长度254位 180 | 使用这个字段的好处是,可以使用DJango内置的EmailValidator进行邮箱地址合法性验证。 181 | """ 182 | EmailField 183 | 184 | 185 | """ 186 | 一个用于保存URL地址的字符串类型 187 | 默认最大长度200。 188 | """ 189 | URLField 190 | 191 | 192 | # 其他 193 | 194 | 195 | """ 196 | Django1.10~ 197 | 64位整数类型自增字段,数字范围更大 198 | 从1到9223372036854775807 199 | """ 200 | BigAutoField 201 | 202 | 203 | """ 204 | 64位整数字段(看清楚,非自增),类似IntegerField 205 | -9223372036854775808 到9223372036854775807。 206 | 在Django的模板表单里体现为一个textinput标签。 207 | """ 208 | BigIntegerField 209 | 210 | 211 | """ 212 | 二进制数据类型。 213 | """ 214 | BinaryField 215 | 216 | 217 | """ 218 | 逗号分隔的整数类型,必须接收一个max_length参数 219 | 220 | 这个我觉得很好,常用于表示较大的金额数目 221 | 222 | 例如1,000,000元。前端省事不少 223 | """ 224 | CommaSeparatedIntegerField 225 | 226 | 227 | """ 228 | 持续时间类型,存储一定期间的时间长度,类似Python中的timedelta。 229 | 常用于进行时间之间的加减运算 230 | """ 231 | DurationField 232 | 233 | 234 | """ 235 | 保存文件路径信息类型 236 | class FilePathField(path=None, match=None, recursive=False, max_length=100, **options)[source] 237 | 238 | path:必选参数。表示一个系统绝对路径。 239 | match:可选参数,一个正则表达式,用于过滤文件名。只匹配基本文件名,不匹配路径。 240 | 例如foo.*\.txt$,只匹配文件名foo23.txt,不匹配bar.txt与foo23.png。 241 | recursive:可选参数,只能是True或者False。默认为False。决定是否包含子目录(是否递归)。 242 | allow_files:可选参数,只能是True或者False。默认为True。决定是否应该将文件名包括在内。 243 | allow_folders: 可选参数,只能是True或者False。默认为False。决定是否应该将目录名包括在内。 244 | allow_files和allow_folders,必须有一个为True。 245 | FilePathField(path="/home/images", match="foo.*", recursive=True) 246 | """ 247 | FilePathField 248 | 249 | 250 | """ 251 | 类似布尔字段,只不过额外允许NULL作为选项之一。 252 | """ 253 | NullBooleanField 254 | 255 | 256 | """ 257 | 正整数字段,包含0,最大2147483647。 258 | """ 259 | PositiveIntegerField 260 | 261 | 262 | """ 263 | 较小的正整数字段,从0到32767。 264 | """ 265 | PositiveSmallIntegerField 266 | 267 | 268 | """ 269 | slug是一个新闻行业的术语。 270 | 一个slug就是一个简短标签 271 | 包含字母、数字、下划线或者连接线,通常用于URLs中。 272 | 可以设置max_length参数,默认为50。 273 | """ 274 | SlugField 275 | 276 | 277 | """ 278 | 小整数,包含-32768到32767。 279 | """ 280 | SmallIntegerField -------------------------------------------------------------------------------- /error_and_debug/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/4 0004. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 -------------------------------------------------------------------------------- /error_and_debug/demo01_try.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/4 0004. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | try: 9 | print("try...") 10 | r = 10 / int('5') 11 | print("result:", r) 12 | 13 | except ZeroDivisionError as e: 14 | print("ZeroDivisionError:", e) 15 | except ValueError as e: 16 | print("ValueError:", e) 17 | except BaseException as e: 18 | print("Error:", e) 19 | else: 20 | print("No Error!") 21 | finally: 22 | print("finally...") 23 | 24 | -------------------------------------------------------------------------------- /error_and_debug/demo2_logging.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/4 0004. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import logging 8 | import sys 9 | 10 | 11 | class FooError(ValueError): 12 | pass 13 | 14 | 15 | def foo(s): 16 | n = int(s) 17 | if n == 0: 18 | raise ValueError('invalid value: %s' % s) 19 | return 10 / int(s) 20 | 21 | 22 | def bar(s): 23 | return foo(s) * 2 24 | 25 | 26 | def bar(): 27 | try: 28 | foo("0") 29 | except ValueError as e: 30 | print("ValueError:", e) 31 | raise 32 | 33 | def test_log_level(): 34 | # set default logging configuration 35 | logger = logging.getLogger() # initialize logging class 36 | logger.setLevel(logging.DEBUG) # default log level 37 | format = logging.Formatter("%(asctime)s - %(message)s") # output format 38 | sh = logging.StreamHandler(stream=sys.stdout) # output to standard output 39 | sh.setFormatter(format) 40 | logger.addHandler(sh) 41 | 42 | # use logging to generate log ouput 43 | logger.info("this is info") 44 | logger.debug("this is debug") 45 | logger.warning("this is warning") 46 | logging.error("this is error") 47 | logger.critical("this is critical") 48 | 49 | 50 | bar() 51 | 52 | # if __name__ == '__main__': 53 | # try: 54 | # bar("0") 55 | # test_log_level() 56 | # except Exception as e: 57 | # logging.exception(e) 58 | # 59 | # print("end") 60 | -------------------------------------------------------------------------------- /error_and_debug/demo3_log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/5 0005. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 记录错误日志到指定目录 8 | 9 | 10 | import logging 11 | import os 12 | 13 | 14 | class MyLogger(object): 15 | def __init__(self, name, path='log'): 16 | log_path = str(os.getcwd()) + '\\' + str(name) + '_' + str(path) + '\\' 17 | self.error_lg = logging.getLogger('error') 18 | self.info_lg = logging.getLogger('info') 19 | if not os.path.exists(log_path): 20 | os.makedirs(log_path) 21 | formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 22 | if len(self.error_lg.handlers) == 0: # 确保只有1个handler 23 | error_h = logging.FileHandler(log_path + 'error.log') 24 | error_h.setFormatter(formatter) 25 | self.error_lg.addHandler(error_h) 26 | if len(self.info_lg.handlers) == 0: 27 | info_h = logging.FileHandler(log_path + 'info.log') 28 | info_h.setFormatter(formatter) 29 | self.info_lg.addHandler(info_h) 30 | 31 | def info(self, msg): 32 | self.info_lg.info(msg) 33 | 34 | def error(self, msg): 35 | self.error_lg.error(msg) 36 | 37 | def release(self): 38 | logging.shutdown() # flushing and closing any handlers (not removing them) 39 | 40 | 41 | if __name__ == '__main__': 42 | t_log = MyLogger("error", "log") 43 | t_log.error('error-5') 44 | t_log.info('info-5') 45 | t_log.release() 46 | 47 | print("End") 48 | -------------------------------------------------------------------------------- /error_and_debug/demo4_debug.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/5 0005. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | import pdb 9 | s = '0' 10 | n = int(s) 11 | # pdb.set_trace() # 运行到这里会自动暂停 12 | print(10 / n) -------------------------------------------------------------------------------- /error_and_debug/demo5_mydict.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/5 0005. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | class Dict(dict): 10 | """ 11 | Simple dict but also support access as x.y style. 12 | 13 | >>> d1 = Dict() 14 | >>> d1['x'] = 100 15 | >>> d1.x 16 | 100 17 | >>> d1.y = 200 18 | >>> d1['y'] 19 | 200 20 | >>> d2 = Dict(a=1, b=2, c='3') 21 | >>> d2.c 22 | '3' 23 | >>> d2['empty'] 24 | Traceback (most recent call last): 25 | ... 26 | KeyError: 'empty' 27 | >>> d2.empty 28 | Traceback (most recent call last): 29 | ... 30 | AttributeError: 'Dict' object has no attribute 'empty' 31 | """ 32 | 33 | def __init__(self, **kwargs): 34 | super(Dict, self).__init__(self, **kwargs) 35 | 36 | # def __getattr__(self, key): 37 | # try: 38 | # return self[key] 39 | # except KeyError: 40 | # raise AttributeError(r"'Dict' object has no attribute '%s'" % key) 41 | 42 | def __setattr__(self, key, value): 43 | self[key] = value 44 | 45 | 46 | if __name__ == '__main__': 47 | import doctest 48 | 49 | doctest.testmod() 50 | -------------------------------------------------------------------------------- /error_and_debug/demo6_setUp_tearDown.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/6 0006. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import unittest 8 | 9 | 10 | class TestDict(unittest.TestCase): 11 | def setUp(self): 12 | print('setUp...') 13 | 14 | def test_isequeals(self): 15 | self.assertEqual(abs(-1), 1) 16 | 17 | def tearDown(self): 18 | print('tearDown...') 19 | -------------------------------------------------------------------------------- /ex_lib/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | 该目录目前都是anaconda自带的,其他库,如pygame之类的,暂未涉及 9 | """ -------------------------------------------------------------------------------- /ex_lib/ball.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/ex_lib/ball.bmp -------------------------------------------------------------------------------- /ex_lib/ex_lib_chardet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | 检测字符编码库 9 | chardet.detect(content) 10 | :param byte_str: The byte sequence to examine. 11 | :type byte_str: ``bytes`` or ``bytearray`` 12 | 13 | https://chardet.readthedocs.io/en/latest/supported-encodings.html 14 | """ 15 | import chardet as chardet 16 | 17 | 18 | def check_char(content): 19 | return chardet.detect(content) 20 | 21 | # 默认只接受byte_str,否则返回TypeError 22 | print("bytes", check_char(b"hello world")) # bytes {'encoding': 'ascii', 'confidence': 1.0, 'language': ''} 23 | # print("str", check_char("hello world")) # TypeError: Expected object of type bytes or bytearray, got: 24 | 25 | 26 | # gbk编码:英文是ascii,中文是GB2312(GBK的上一版中文字符集),language字段指出的语言是'Chinese' 27 | print("str1", check_char("hello world".encode("gbk"))) # str1 {'encoding': 'ascii', 'confidence': 1.0, 'language': ''} 28 | print("str2", check_char("老子回来啦".encode("gbk"))) # str2 {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'} 29 | 30 | 31 | # utf-8编码: 英文还是ascii,中文是utf-8了,但是language没有指出,是因为utf-8适用的太多了 32 | print("str3", check_char("hello world".encode("utf-8"))) # str3 {'encoding': 'ascii', 'confidence': 1.0, 'language': ''} 33 | print("str4", check_char("老子回来啦".encode("utf-8"))) # str4 {'encoding': 'utf-8', 'confidence': 0.9690625, 'language': ''} 34 | -------------------------------------------------------------------------------- /ex_lib/ex_lib_pillow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/18 0018. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | from PIL import Image, ImageDraw, ImageFont, ImageFilter 8 | import random 9 | 10 | """ 11 | PIL:Python Imaging Library,Python平台事实上的图像处理标准库。 12 | https://pillow.readthedocs.io 13 | 现在主要是志愿者在维护 14 | """ 15 | 16 | 17 | # # 图像缩放 18 | # # 打开图片 os.path.abspath(os.path.join(os.getcwd(), "../img/logo.png")) 19 | # img = Image.open("../img/logo.png") 20 | # # 获得图像尺寸: 21 | # w, h = img.size 22 | # print('Original image size: %sx%s' % (w, h)) 23 | # # 缩放到50%: 24 | # img.thumbnail((w // 2, h // 2)) 25 | # print('Resize image to: %sx%s' % (w // 2, h // 2)) 26 | # # 把缩放后的图像用jpeg格式保存: 27 | # img.save('../img/logo_thumbnail.png', 'png') 28 | 29 | 30 | # # 其他功能如切片、旋转、滤镜、输出文字、调色板等一应俱全。 31 | # # 模糊效果 32 | # img2 = img.filter(ImageFilter.BLUR) 33 | # img2.save("../img/logo_thumbnail_blur.png", "png") 34 | 35 | 36 | # PIL的ImageDraw提供了一系列绘图方法,让我们可以直接绘图。比如要生成字母验证码图片 37 | def random_char(): # 字母 38 | return chr(random.randint(65, 90)) 39 | 40 | 41 | def random_color(): # 颜色 42 | return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255) 43 | 44 | 45 | def random_color2(): 46 | return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127) 47 | 48 | 49 | width = 60 * 4 50 | height = 60 51 | image = Image.new("RGB", (width, height), (255, 255, 255)) 52 | font = ImageFont.truetype("C:\Windows\Fonts\Arial.ttf", 36) # 创建font 53 | draw = ImageDraw.Draw(image) # 创建draw 54 | for x in range(width): # 填充像素 55 | for y in range(height): 56 | draw.point((x, y), fill=random_color()) 57 | 58 | for t in range(4): # 写字 59 | draw.text((60 * t + 10, 10), random_char(), font=font, fill=random_color2()) 60 | 61 | 62 | image = image.filter(ImageFilter.BLUR) # 模糊 63 | image.save("code.png", "png") 64 | -------------------------------------------------------------------------------- /ex_lib/ex_lib_psutils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | psutil是一个用于检索信息的跨平台库 9 | 运行进程和系统利用率(CPU、内存、磁盘、网络,在Python中传感器)。 10 | 11 | 支持平台: 12 | - Linux 13 | - Windows 14 | - OSX 15 | - FreeBSD 16 | - OpenBSD 17 | - NetBSD 18 | - Sun Solaris 19 | - AIX 20 | """ 21 | import psutil 22 | 23 | print("-----------cpu_count-----------") 24 | print(psutil.cpu_count()) # 返回系统中逻辑cpu的数量 25 | print("-----------cpu_freq-----------") 26 | print(psutil.cpu_freq()) # 返回CPU频率 27 | print("-----------cpu_percent-----------") 28 | print(psutil.cpu_percent()) # 返回当前系统CPU利用率(float类型) 29 | print("-----------cpu_stats-----------") 30 | print(psutil.cpu_stats()) # 返回CPU统计数据 31 | print("-----------cpu_times-----------") 32 | print(psutil.cpu_times()) # 返回系统范围内的CPU时间。 33 | print("-----------cpu_times_percent-----------") 34 | print(psutil.cpu_times_percent()) # 对于每个特定的CPU时间提供利用率,由cpu_times()返回。 35 | print("-----------boot_time-----------") 36 | print(psutil.boot_time()) # 返回从1970以来以秒表示的系统启动时间 37 | print("-----------users-----------") 38 | print(psutil.users()) # 返回当前连接在系统上的用户列表 39 | print("-----------test-----------") 40 | print(psutil.test()) # 列出所有当前正在运行的进程信息 41 | 42 | """ 43 | -----------cpu_count----------- 44 | 4 45 | -----------cpu_freq----------- 46 | scpufreq(current=3168.0, min=0.0, max=3201.0) 47 | -----------cpu_percent----------- 48 | 0.0 49 | -----------cpu_stats----------- 50 | scpustats(ctx_switches=861048211, interrupts=148032987, soft_interrupts=0, syscalls=1186688671) 51 | -----------cpu_times----------- 52 | scputimes(user=6015.96044921875, system=2641.171875, idle=79255.78125, interrupt=93.52259969711304, dpc=523.3521823883057) 53 | -----------cpu_times_percent----------- 54 | scputimes(user=0.0, system=0.0, idle=0.0, interrupt=0.0, dpc=0.0) 55 | -----------boot_time----------- 56 | 1513644441.0 57 | -----------users----------- 58 | [suser(name='TaoYuan', terminal=None, host='0.0.0.0', started=1513644451.0, pid=None)] 59 | -----------test----------- 60 | USER PID %MEM VSZ RSS TTY START TIME COMMAND 61 | SYSTEM 0 ? ? 24 ? 08:47 00:55 System Idle Process 62 | SYSTEM 4 ? 120 368 ? 08:47 05:13 System 63 | 320 ? 544 1216 ? 08:47 00:00 smss.exe 64 | 332 0.2 14004 20068 ? 08:47 00:17 svchost.exe 65 | 496 0.3 21472 37028 ? 08:47 00:30 svchost.exe 66 | 500 ? 2392 5416 ? 08:47 00:00 csrss.exe 67 | 516 0.2 9904 19112 ? 08:47 00:00 svchost.exe 68 | 656 ? 1824 5384 ? 08:47 00:00 wininit.exe 69 | 664 0.7 4196 90228 ? 08:47 00:54 csrss.exe 70 | 712 0.1 3476 8488 ? 08:47 00:00 winlogon.exe 71 | 756 0.1 6044 10336 ? 08:47 00:07 services.exe 72 | 768 0.1 5900 13452 ? 08:47 00:23 lsass.exe 73 | 776 ? 2976 4968 ? 08:47 00:01 lsm.exe 74 | 876 0.1 4364 10164 ? 08:47 00:03 svchost.exe 75 | 952 0.1 5412 9540 ? 08:47 00:08 svchost.exe 76 | 1060 0.1 3424 8216 ? 08:47 00:00 svchost.exe 77 | 1092 0.1 5616 11364 ? 08:47 00:00 svchost.exe 78 | 1184 0.4 44764 54276 ? 08:47 00:09 ZhuDongFangYu.exe 79 | TaoYuan 1224 0.3 29080 34416 ? 09:11 00:00 chrome.exe 80 | 1272 0.2 17796 19908 ? 08:47 00:06 svchost.exe 81 | TaoYuan 1320 0.7 10948 82148 ? 08:47 00:00 taskeng.exe 82 | TaoYuan 1416 0.1 8192 16160 ? 09:11 00:00 conhost.exe 83 | 1452 0.1 6332 12352 ? 08:47 00:00 spoolsv.exe 84 | ... 85 | """ 86 | 87 | print("-----------Process-----------") 88 | print(psutil.Process(3776)) # 获取指定进程ID=3776,其实就是当前Python交互环境 89 | print("-----------pids-----------") 90 | print(psutil.pids()) # 所有进程id 91 | print("-----------pid_exists-----------") 92 | print(psutil.pid_exists()) # 当前pid是否在列表中 93 | print("-----------Process Other-----------") 94 | # Process是一个类,其他信息运维可以看看,我就不看了 -------------------------------------------------------------------------------- /ex_lib/ex_lib_pygame.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | https://www.pygame.org/docs/ 9 | 10 | WINDOWS: 11 | anaconda lib 12 | py -m pygame.examples.aliens 13 | 14 | or run python in cmd 15 | py -m pip install pygame --user 16 | py -m pygame.examples.aliens 17 | 18 | 19 | LINUX 20 | LINUX 自带python2 21 | Debian/Ubuntu/Mint 22 | sudo apt-get install python3-pygame 23 | python3 -m pygame.examples.aliens 24 | 25 | Fedora/Red hat 26 | sudo yum install python3-pygame 27 | python3 -m pygame.examples.aliens 28 | """ 29 | 30 | import pygame 31 | import sys 32 | 33 | # https://www.pygame.org/docs/tut/PygameIntro.html 34 | pygame.init() 35 | 36 | size = width, height = 840, 480 37 | speed = [1, 1] 38 | black = 0, 0, 0 39 | 40 | screen = pygame.display.set_mode(size) 41 | 42 | ball = pygame.image.load("ball.bmp") 43 | ballrect = ball.get_rect() 44 | 45 | while 1: 46 | for event in pygame.event.get(): 47 | if event.type == pygame.QUIT: sys.exit() 48 | 49 | ballrect = ballrect.move(speed) 50 | if ballrect.left < 0 or ballrect.right > width: 51 | speed[0] = -speed[0] 52 | if ballrect.top < 0 or ballrect.bottom > height: 53 | speed[1] = -speed[1] 54 | 55 | screen.fill(black) 56 | screen.blit(ball, ballrect) 57 | pygame.display.flip() 58 | -------------------------------------------------------------------------------- /ex_lib/ex_lib_pyqt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | 这块我也不太懂 9 | 而且不愿意装QT环境 10 | 所以还是看源码吧 11 | 12 | PyQt5 13 | ===== 14 | 15 | For PyQt5, you don't have to set anything as it will be used automatically:: 16 | 17 | >>> from qtpy import QtGui, QtWidgets, QtCore 18 | >>> print(QtWidgets.QWidget) 19 | 20 | 21 | PySide2 22 | ====== 23 | 24 | Set the QT_API environment variable to 'pyside2' before importing other 25 | packages:: 26 | 27 | >>> import os 28 | >>> os.environ['QT_API'] = 'pyside2' 29 | >>> from qtpy import QtGui, QtWidgets, QtCore 30 | >>> print(QtWidgets.QWidget) 31 | 32 | PyQt4 33 | ===== 34 | 35 | Set the ``QT_API`` environment variable to 'pyqt' before importing any python 36 | package:: 37 | 38 | >>> import os 39 | >>> os.environ['QT_API'] = 'pyqt' 40 | >>> from qtpy import QtGui, QtWidgets, QtCore 41 | >>> print(QtWidgets.QWidget) 42 | 43 | PySide 44 | ====== 45 | 46 | Set the QT_API environment variable to 'pyside' before importing other 47 | packages:: 48 | 49 | >>> import os 50 | >>> os.environ['QT_API'] = 'pyside' 51 | >>> from qtpy import QtGui, QtWidgets, QtCore 52 | >>> print(QtWidgets.QWidget) 53 | """ 54 | 55 | -------------------------------------------------------------------------------- /ex_lib/ex_lib_requests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | """ 9 | 我们已经讲解了Python内置的urllib模块,用于访问网络资源。 10 | 但是,它用起来比较麻烦,而且,缺少很多实用的高级功能。 11 | 12 | 更好的方案是使用requests。它是一个Python第三方库,处理URL资源特别方便。 13 | 14 | 1. 获得bytes对象: r.content 15 | 2. 检测编码: r.encoding 16 | 3. 获取json: r.json() 17 | 4. 传入header(dict): r = requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'}) 18 | 5. post + data请求: r = requests.post('https://accounts.douban.com/login', data={'form_email': 'abc@example.com', 'form_password': '123456'}) 19 | 6. requests默认使用application/x-www-form-urlencoded对POST数据编码 20 | 7. json post: r = requests.post(url, json=params) # 内部自动序列化为JSON 21 | 8. file post: 在读取文件时,注意务必使用'rb'即二进制模式读取,这样获取的bytes长度才是文件的长度 22 | upload_files = {'file': open('report.xls', 'rb')} 23 | r = requests.post(url, files=upload_files) 24 | 25 | 9. 获取响应头: r.headers 头信息: r.headers['Content-Type'] 26 | 10. 获取cookie: r.cookies['ts'] 27 | 11. 传入cookie: r = requests.get(url, cookies={'token': '12345', 'status': 'working')) 28 | 12. 超时参数: r = requests.get(url, timeout=2.5) # 单位: s 29 | """ 30 | import requests 31 | 32 | # get 33 | r = requests.get('https://www.python.org') 34 | print(r.status_code) 35 | print(b'Python is a programming language' in r.content) 36 | 37 | print("--------------get args-------------") 38 | r = requests.get('https://www.douban.com/search', params={'q': 'python', 'cat': '1001'}) 39 | print(r.url) 40 | 41 | print("-------------post------------") 42 | payload = dict(key1='value1', key2='value2') 43 | r = requests.post('http://httpbin.org/post', data=payload) 44 | print(r.text) 45 | -------------------------------------------------------------------------------- /gui_demo/demo1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-15 18:38:32 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : $Id$ 7 | 8 | from tkinter import * 9 | from tkinter import messagebox 10 | 11 | text = "Hello TaoYuan" 12 | 13 | 14 | class Application(Frame): 15 | def __init__(self, master=None): 16 | Frame.__init__(self, master) 17 | self.nameInput = None 18 | self.pack() 19 | self.create_widgets() 20 | 21 | def create_widgets(self): 22 | self.helloLabel = Label(self, text=text) 23 | self.helloLabel.pack() 24 | 25 | self.nameInput = Entry(self) 26 | self.nameInput.pack() 27 | self.alertButton = Button(self, text="alert", command=self.sound) 28 | self.alertButton.pack() 29 | 30 | self.quitButton = Button(self, text='quit', command=self.quit) 31 | self.quitButton.pack() 32 | 33 | def sound(self): 34 | name = self.nameInput.get() or 'welcome to I_YIN' 35 | messagebox.showinfo('Message', 'Hello, %s' % name) 36 | 37 | 38 | app = Application() 39 | # 设置窗口标题: 40 | app.master.title(text) 41 | # 主消息循环: 42 | app.mainloop() 43 | -------------------------------------------------------------------------------- /gui_demo/demo2.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import tkinter.messagebox as messagebox 3 | 4 | 5 | class Application(Frame): 6 | def __init__(self, master=None): 7 | Frame.__init__(self, master) 8 | self.pack() 9 | self.createWidgets() 10 | 11 | def createWidgets(self): 12 | self.nameInput = Entry(self) 13 | self.nameInput.pack() 14 | self.alertButton = Button(self, text='Hello', command=self.hello) 15 | self.alertButton.pack() 16 | 17 | def hello(self): 18 | name = self.nameInput.get() or 'world' 19 | messagebox.showinfo('Message', 'Hello, %s' % name) 20 | 21 | 22 | app = Application() 23 | app.master.title('Hello World') 24 | app.mainloop() 25 | -------------------------------------------------------------------------------- /img/custom_class_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/custom_class_1.png -------------------------------------------------------------------------------- /img/custom_class_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/custom_class_2.png -------------------------------------------------------------------------------- /img/custom_class_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/custom_class_3.png -------------------------------------------------------------------------------- /img/distribute_process_error01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/distribute_process_error01.png -------------------------------------------------------------------------------- /img/distribute_process_error02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/distribute_process_error02.png -------------------------------------------------------------------------------- /img/distribute_process_ok01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/distribute_process_ok01.png -------------------------------------------------------------------------------- /img/err_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/err_01.png -------------------------------------------------------------------------------- /img/err_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/err_02.png -------------------------------------------------------------------------------- /img/local_file_server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/local_file_server.png -------------------------------------------------------------------------------- /img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/logo.png -------------------------------------------------------------------------------- /img/logo_thumbnail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/logo_thumbnail.png -------------------------------------------------------------------------------- /img/logo_thumbnail_blur.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/img/logo_thumbnail_blur.png -------------------------------------------------------------------------------- /multitask/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/11 0011. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 -------------------------------------------------------------------------------- /multitask/test01_multi_progress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/10. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | import os, time, random 10 | from multiprocessing import Process, Pool 11 | 12 | 13 | # print("Process (%s) start..." % os.getpid()) 14 | # Only works on Unix/Linux/Mac: 15 | # pid = os.fork() 16 | # if pid == 0: 17 | # print("I am child Process (%s) and my parent is %s" % (os.getpid(), os.getpid())) 18 | # else: 19 | # print("I (%s) just Created a child process (%s)" % (os.getpid(), pid)) 20 | 21 | def run_proc(name): 22 | print("Process child process %s (%s)..." % (name, os.getpid())) 23 | 24 | 25 | def long_time_task(name): 26 | print("Run task %s (%s)..." % (name, os.getpid())) 27 | start = time.time() 28 | time.sleep(random.random() * 3) 29 | end = time.time() 30 | print("Task %s runs %0.2f seconds." % (name, end - start)) 31 | 32 | 33 | if __name__ == '__main__': 34 | print("Parent process %s " % os.getpid()) 35 | # # 创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动 36 | # p = Process(target=run_proc, args=("test",)) 37 | # print("child process will start.") 38 | # p.start() 39 | # p.join() # join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步 40 | # print("child process end.") 41 | 42 | p1 = Pool(5) # Pool()线程池数量,默认是cpu核心数 43 | for i in range(5): 44 | p1.apply_async(long_time_task, args=(i,)) 45 | print("waiting for all subprocesses done...") 46 | p1.close() 47 | p1.join() 48 | print("all subprocesses done.") 49 | -------------------------------------------------------------------------------- /multitask/test02_sub_progress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/11 0011. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 很多时候,子进程并不是自身,而是一个外部进程。我们创建了子进程后,还需要控制子进程的输入和输出。 8 | 9 | import subprocess 10 | 11 | print("$ nslookup www.python.org") 12 | r = subprocess.call(["nslookup", "www.python.org"]) 13 | 14 | print("Exit code:", r) 15 | -------------------------------------------------------------------------------- /multitask/test03_queue.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/11 0011. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | from multiprocessing import Process, Queue 10 | import os, time, random 11 | 12 | 13 | # 写数据进程执行的代码 14 | def write(q): 15 | print("process to write: %s" % os.getpid()) 16 | for value in ["A", "B", "C"]: 17 | print("Put %s to queue..." % value) 18 | q.put(value) 19 | time.sleep(random.random()) 20 | 21 | 22 | # 读数据进程执行的代码: 23 | def read(q): 24 | print("process to read: %s" % os.getpid()) 25 | while True: 26 | value = q.get(True) 27 | print("Get %s from queue." % value) 28 | 29 | 30 | if __name__ == '__main__': 31 | # 父进程创建Queue,并传给各子进程 32 | q = Queue() 33 | pw = Process(target=write, args=(q,)) 34 | pr = Process(target=read, args=(q,)) 35 | -------------------------------------------------------------------------------- /multitask/test04_distribute_process_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/12 0012. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | import queue 10 | import random 11 | from multiprocessing.managers import BaseManager 12 | 13 | # 发送任务的队列: 14 | task_queue = queue.Queue() 15 | # 接收结果的队列: 16 | result_queue = queue.Queue() 17 | 18 | 19 | # 从BaseManager继承的QueueManager: 20 | class QueueManager(BaseManager): 21 | pass 22 | 23 | 24 | # 把两个Queue都注册到网络上, callable参数关联了Queue对象: 25 | QueueManager.register('get_task_queue', callable=lambda: task_queue) 26 | QueueManager.register('get_result_queue', callable=lambda: result_queue) 27 | # 绑定端口5000, 设置验证码'abc': 28 | manager = QueueManager(address=('', 5000), authkey=b'abc') 29 | # 启动Queue: 30 | manager.start() 31 | # 获得通过网络访问的Queue对象: 32 | task = manager.get_task_queue() 33 | result = manager.get_result_queue() 34 | # 放几个任务进去: 35 | for i in range(10): 36 | n = random.randint(0, 10000) 37 | print('Put task %d...' % n) 38 | task.put(n) 39 | # 从result队列读取结果: 40 | print('Try get results...') 41 | for i in range(10): 42 | r = result.get(timeout=10) 43 | print('Result: %s' % r) 44 | # 关闭: 45 | manager.shutdown() 46 | print('master exit.') 47 | -------------------------------------------------------------------------------- /multitask/test05_distribute_process_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/12 0012. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | import queue 10 | import time 11 | from multiprocessing.managers import BaseManager 12 | 13 | 14 | # 创建类似的QueueManager: 15 | class QueueManager(BaseManager): 16 | pass 17 | 18 | 19 | # 由于这个QueueManager只从网络上获取Queue,所以注册时只提供名字: 20 | QueueManager.register('get_task_queue') 21 | QueueManager.register('get_result_queue') 22 | 23 | # 连接到服务器,也就是运行task_master.py的机器: 24 | server_addr = '127.0.0.1' 25 | print('Connect to server %s...' % server_addr) 26 | # 端口和验证码注意保持与task_master.py设置的完全一致: 27 | m = QueueManager(address=(server_addr, 5000), authkey=b'abc') 28 | # 从网络连接: 29 | m.connect() 30 | # 获取Queue的对象: 31 | task = m.get_task_queue() 32 | result = m.get_result_queue() 33 | # 从task队列取任务,并把结果写入result队列: 34 | for i in range(10): 35 | try: 36 | n = task.get(timeout=1) 37 | print('run task %d * %d...' % (n, n)) 38 | r = '%d * %d = %d' % (n, n, n * n) 39 | time.sleep(1) 40 | result.put(r) 41 | except queue.Empty: 42 | print('task queue is empty.') 43 | # 处理结束: 44 | print('worker exit.') 45 | -------------------------------------------------------------------------------- /my_res/idea_active_proxy.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/my_res/idea_active_proxy.exe -------------------------------------------------------------------------------- /oop_demo/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/29 0029 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 -------------------------------------------------------------------------------- /oop_demo/student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-30 17:54:54 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # @des : 请把下面的Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性 8 | 9 | 10 | class Student(object): 11 | def __init__(self, name, gender): 12 | self.name = name 13 | self.__gender = gender 14 | 15 | def get_gender(self): 16 | return self.__gender 17 | 18 | def set_gender(self, gender): 19 | if gender.__str__() == 'male' or gender.__str__() == 'female': 20 | self.__gender = gender 21 | else: 22 | raise ValueError('不男不女') 23 | 24 | 25 | if __name__ == '__main__': 26 | # 测试: 27 | bart = Student('Bart', 'male') 28 | if bart.get_gender() != 'male': 29 | print('测试失败!') 30 | else: 31 | bart.set_gender('female') 32 | if bart.get_gender() != 'female': 33 | print('测试失败!') 34 | else: 35 | try: 36 | bart.set_gender('人妖') 37 | print('测试失败!') 38 | except ValueError: 39 | print('测试成功!') 40 | -------------------------------------------------------------------------------- /oop_demo/test01.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/29 0029 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | # 简介,类和实例 8 | 9 | 10 | # 面向对象的程序设计思想 11 | # 我们首选思考的不是程序的执行流程,而是Student这种数据类型应该被视为一个对象 12 | # 这个对象拥有name和score这两个属性(Property)。 13 | # 如果要打印一个学生的成绩, 14 | # 首先必须创建出这个学生对应的对象, 15 | # 然后给对象发一个print_score消息 16 | # 让对象自己把自己的数据打印出来。 17 | class Student(object): 18 | """docstring for Student""" 19 | 20 | def __init__(self, name, score, *remark): 21 | self.name = name 22 | self.score = score 23 | self.remark = remark 24 | 25 | def print_score(self): 26 | print("{0} {1} {2}".format(self.name, self.score, self.remark)) 27 | 28 | def is_pass(self): 29 | if 0 < self.score < 60: 30 | return "不及格" 31 | elif 60 <= self.score < 90: 32 | return "及格" 33 | elif 90 <= self.score <= 100: 34 | return "优等生" 35 | else: 36 | return "成绩作废!归零" 37 | 38 | 39 | # 面向过程 40 | # 假设我们要处理学生的成绩表,为了表示一个学生的成绩,面向过程的程序可以用一个dict表示: 41 | std1 = {'name': 'Michael', 'score': 98} 42 | std2 = {'name': 'Bob', 'score': 81} 43 | 44 | 45 | # 而处理学生成绩可以通过函数实现,比如打印学生的成绩: 46 | def print_score(std): 47 | print('%s: %s' % (std['name'], std['score'])) 48 | 49 | 50 | if __name__ == '__main__': 51 | print('----------------') 52 | Student("zhangsan", 59, "命不好").print_score() 53 | Student("lisi", 99, "屌爆了").print_score() 54 | print('----------------') 55 | print_score(std1) 56 | print_score(std2) 57 | print('----------------') 58 | 59 | # 变量stu指向的就是一个Student的实例 60 | stu = Student("wangwu", 61, "运气好") 61 | # 创建实例的时候已经有值了,所以可以直接打印出来 62 | print(stu.name) 63 | 64 | # 可以对name属性重新赋值 65 | stu.name = "zhaoliu" 66 | print(stu.name) 67 | 68 | # 也可以自定义一个新属性 69 | stu.address = "深圳" 70 | print(stu.address) 71 | print('----------------') 72 | lilei = Student('李雷', 99) 73 | hanmeimei = Student('韩梅梅', 59) 74 | print(lilei.name, lilei.is_pass()) 75 | print(hanmeimei.name, hanmeimei.is_pass()) 76 | -------------------------------------------------------------------------------- /oop_demo/test02.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-30 11:26:38 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # 继承和多态 8 | 9 | 10 | class Animal(object): 11 | def run(self): 12 | print('Animal is running...') 13 | 14 | 15 | class Dog(Animal): 16 | def dog_run(self): 17 | print('Dog is running...') 18 | 19 | 20 | # 子类可以继承父类的所有功能 21 | dog = Dog() 22 | dog.run() 23 | dog.dog_run() 24 | 25 | print('-' * 30) 26 | 27 | a = list() 28 | b = Animal() 29 | c = Dog() 30 | 31 | print(isinstance(a, list)) 32 | print(isinstance(b, Animal)) 33 | print(isinstance(c, Dog)) 34 | # 上述没错,但是c同时也可以是Animal 35 | print(isinstance(c, Animal)) 36 | 37 | # 获取该对象所有的属性和方法 38 | print(dir(Dog())) 39 | 40 | 41 | -------------------------------------------------------------------------------- /oop_demo/test03_property.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/1 0001. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | class Student(object): 10 | @property 11 | def score(self): 12 | return self._score 13 | 14 | @score.setter 15 | def score(self, value): 16 | if not isinstance(value, int): 17 | raise ValueError("score must be an integer!") 18 | if value < 0 or value > 100: 19 | raise ValueError("score must between 0~100") 20 | self._score = value 21 | 22 | def birth(self): 23 | return 200-self._score 24 | 25 | 26 | if __name__ == '__main__': 27 | s = Student() 28 | s.score = 60 29 | print(s.score) 30 | print(s.birth()) 31 | -------------------------------------------------------------------------------- /oop_demo/test04_extend.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/1 0001. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | import inspect 9 | 10 | class G(object): 11 | pass 12 | 13 | class D(object): 14 | def __init__(self): 15 | print("D") 16 | 17 | 18 | class E(object): 19 | def __init__(self): 20 | print("E") 21 | 22 | 23 | class F(object): 24 | def __init__(self): 25 | print("F") 26 | 27 | 28 | class C(D, F): 29 | def __init__(self): 30 | print("C") 31 | 32 | 33 | class B(E, G): 34 | def __init__(self): 35 | print("B") 36 | 37 | 38 | class A(B, C): 39 | def __init__(self): 40 | print("A") 41 | 42 | 43 | if __name__ == '__main__': 44 | print(inspect.getmro(A)) 45 | -------------------------------------------------------------------------------- /oop_demo/test05_custom_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/2 0002. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 定制类 8 | 9 | 10 | # __str__ 和 __repr__ 11 | class Student(object): 12 | """docstring for Student""" 13 | 14 | def __init__(self, name): 15 | self.name = name 16 | 17 | def __str__(self): 18 | return "Student object {0}".format(self.name) 19 | 20 | __repr__ = __str__ # 格式化栈显示 21 | 22 | 23 | # __iter__该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。 24 | class Fib(object): 25 | def __init__(self): 26 | self.a, self.b = 0, 1 # 初始化两个计数器 27 | 28 | def __iter__(self): 29 | return self # 实例本身就是迭代对象 30 | 31 | def __next__(self): 32 | self.a, self.b = self.b, self.a + self.b # 计算下一个值 33 | if self.a > 100000: 34 | raise StopIteration() 35 | return self.a # 返回下一个值 36 | 37 | # __getitem__ :把__iter__变成数组 38 | # 与之对应的是__setitem__()方法,把对象视作list或dict来对集合赋值。 39 | # 还有一个__delitem__()方法,用于删除某个元素 40 | def __getitem__(self, n): 41 | a, b = 1, 1 42 | for x in range(n): 43 | a, b = b, a + b 44 | return a 45 | 46 | 47 | # __getattr__ 正常情况下,当我们调用类方法或属性时,不存在就报错 48 | # 为了避免这个错误,可以用__getattr__动态返回一个属性 49 | class Chain(object): 50 | """docstring for Chain""" 51 | 52 | def __init__(self, path=""): 53 | self.path = path 54 | 55 | def __getattr__(self, path): 56 | return Chain("{0}/{1}".format(self.path, path)) 57 | # return Chain("%s/%s" % (self.path, path)) 58 | 59 | def __str__(self): 60 | return self.path 61 | 62 | __repr__ = __str__ 63 | 64 | 65 | # 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用 66 | class Student_call(object): 67 | def __init__(self, name): 68 | self.name = name 69 | 70 | def __call__(self): 71 | print("My name is {0}".format(self.name)) 72 | 73 | # s = Student_call("taoyuan") 74 | # print(s()) 75 | -------------------------------------------------------------------------------- /oop_demo/test06_enum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/2 0002. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 把Student的gender属性改造为枚举类型,可以避免使用字符串 8 | from enum import Enum, unique 9 | 10 | 11 | @unique 12 | class Gender(Enum): 13 | Male = 0 14 | Female = 1 15 | 16 | 17 | class Student(object): 18 | def __init__(self, name, gender): 19 | self.name = name 20 | self.gender = gender 21 | 22 | 23 | # 测试: 24 | lilei = Student('lilei', Gender.Male) 25 | hanmeimei = Student("hanmeimei", Gender.Female) 26 | if lilei.gender == Gender.Male and hanmeimei.gender == Gender.Female: 27 | print('测试通过!') 28 | else: 29 | print('测试失败!') 30 | -------------------------------------------------------------------------------- /oop_demo/test07_metaclass.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/4 0004. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | class ListMetaclass(type): 10 | def __new__(cls, name, bases, attrs): 11 | attrs["add"] = lambda self, value: self.append(value) 12 | return type.__new__(cls, name, bases, attrs) 13 | 14 | 15 | class MyList(list, metaclass=ListMetaclass): 16 | pass 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /oop_demo/test08_orm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/4 0004. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import inspect 8 | 9 | 10 | class Field(object): 11 | def __init__(self, name, column_type): 12 | self.name = name 13 | self.column_type = column_type 14 | 15 | def __str__(self): 16 | return "<%s:%s>" % (self.__class__.__name__, self.name) 17 | 18 | 19 | class IntegerField(Field): 20 | def __init__(self, name): 21 | super(IntegerField, self).__init__(name, "bigint") 22 | 23 | 24 | class StringField(Field): 25 | def __init__(self, name): 26 | super(StringField, self).__init__(name, "varchar(20)") 27 | 28 | 29 | class ModelMetaclass(type): 30 | def __new__(mcs, name, bases, attrs): 31 | if name == "Model": 32 | return type.__new__(mcs, name, bases, attrs) 33 | print("Found Model:%s" % name) 34 | mappings = dict() 35 | for k, v in attrs.items(): 36 | if isinstance(v, Field): 37 | print("Found mappings:%s --> %s" % (k, v)) 38 | mappings[k] = v 39 | for k in mappings.keys(): 40 | attrs.pop(k) 41 | attrs['__mappings__'] = mappings # 保存属性和列的映射关系 42 | attrs['__table__'] = name # 假设表名和类名一致 43 | return type.__new__(mcs, name, bases, attrs) 44 | 45 | 46 | class Model(dict, metaclass=ModelMetaclass): 47 | def __init__(self, **kw): 48 | super(Model, self).__init__(**kw) 49 | 50 | def __getattr__(self, key): # 属性校验 51 | try: 52 | return self[key] 53 | except KeyError: 54 | raise AttributeError(r"'Model' object has no attribute '%s'" % key) 55 | 56 | def __setattr__(self, key, value): # set 57 | self[key] = value 58 | 59 | def save(self): # 保存 60 | fields = [] 61 | params = [] 62 | args = [] 63 | for k, v in self.__mappings__.items(): 64 | fields.append(v.name) 65 | params.append('?') 66 | args.append(getattr(self, k, None)) 67 | 68 | # 连接数据库驱动即可真正连接 69 | sql = "insert into %s (%s) values (%s)" % (self.__table__, ','.join(fields), ','.join(params)) 70 | print('SQL: %s' % sql) 71 | print('ARGS: %s' % str(args)) 72 | 73 | def delete(self): # 删 74 | # 连接数据库驱动即可真正连接 75 | sql = "delete from %s" % self.__table__ 76 | print('SQL: %s' % sql) 77 | 78 | def update(self): # 改 79 | fields = [] 80 | params = [] 81 | args = [] 82 | for k, v in self.__mappings__.items(): 83 | fields.append(v.name) 84 | params.append('?') 85 | args.append(getattr(self, k, None)) 86 | 87 | # 连接数据库驱动即可真正连接 88 | sql = "update %s set %s=%s" % (self.__table__, ','.join(fields), ','.join(params)) 89 | print('SQL: %s' % sql) 90 | print('ARGS: %s' % str(args)) 91 | 92 | def find(self): # 查 93 | # 连接数据库驱动即可真正连接 94 | sql = "select * from %s" % self.__table__ 95 | print('SQL: %s' % sql) 96 | 97 | 98 | class User(Model): 99 | # 定义类属性到数据库列的映射 100 | id = IntegerField("id") 101 | username = StringField("username") 102 | password = StringField("password") 103 | email = StringField("email") 104 | 105 | 106 | if __name__ == '__main__': 107 | # 创建实例 108 | u = User(id=1, username="TaoYuan", password="123456", email="1876665310@qq.com") 109 | 110 | # 增删改查 111 | u.save() 112 | print('-' * 30) 113 | u.delete() 114 | print('-' * 30) 115 | u.update() 116 | print('-' * 30) 117 | u.find() 118 | print('-' * 15, "调用顺序如下", '-' * 15) 119 | print(inspect.getmro(User)) 120 | -------------------------------------------------------------------------------- /other_tools/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 -------------------------------------------------------------------------------- /other_tools/file_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/1/25 0025. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | import os 7 | import time 8 | 9 | """ 10 | 文件工具类 11 | """ 12 | 13 | # 把时间戳转化为时间: 1479264792 to 2016-11-16 10:53:12 14 | def time_stamp_to_time(timestamp): 15 | time_struct = time.localtime(timestamp) 16 | return time.strftime('%Y-%m-%d %H:%M:%S', time_struct) 17 | 18 | 19 | # 获取文件的大小,结果保留两位小数,单位为MB 20 | def get_file_size(file_path): 21 | file_path = file_path.encode("utf-8") 22 | file_size = os.path.getsize(file_path) 23 | file_size = file_size / float(1024 * 1024) 24 | return round(file_size, 2) 25 | 26 | 27 | # 获取文件的访问时间 28 | def get_file_access_time(file_path): 29 | file_path = file_path.encode("utf-8") 30 | t = os.path.getatime(file_path) 31 | return time_stamp_to_time(t) 32 | 33 | 34 | # 获取文件的创建时间 35 | def get_file_create_time(file_path): 36 | file_path = file_path.encode("utf-8") 37 | t = os.path.getctime(file_path) 38 | return time_stamp_to_time(t) 39 | 40 | 41 | # 获取文件的修改时间 42 | def get_file_modify_time(file_path): 43 | file_path = file_path.encode("utf-8") 44 | t = os.path.getmtime(file_path) 45 | return time_stamp_to_time(t) 46 | -------------------------------------------------------------------------------- /other_tools/send_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/1/23 0023. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | """ 7 | 来自django框架,实测可用,需要配置 8 | """ 9 | import os 10 | from django.core.mail import send_mail, EmailMultiAlternatives 11 | 12 | 13 | os.environ['DJANGO_SETTINGS_MODULE'] = 'MyBlog.settings' 14 | 15 | 16 | if __name__ == '__main__': 17 | 18 | subject = "来自TaoYuan的测试邮件" 19 | from_email = "xxx@163.com" 20 | to = ["xxx@qq.com"] 21 | text_content = "Github: https://github.com/seeways CSDN: http://blog.csdn.net/lftaoyuan" 22 | html_content = "

Github:seeways


CSDN:TaoYuan

" 24 | 25 | # send_mail(主题, 内容, 发送者, 接收列表,其他默认参数) 26 | # send_mail( 27 | # subject, 28 | # text_content, 29 | # from_email, 30 | # to, 31 | # html_message=html_content 32 | # ) 33 | 34 | # EmailMultiAlternatives 35 | 36 | # 优先发送html_content, html内容无效时,发送text 37 | msg = EmailMultiAlternatives(subject, text_content, from_email, to) 38 | msg.attach_alternative(html_content, "text/html") 39 | msg.send() -------------------------------------------------------------------------------- /other_tools/urllib_download_big_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/1/10 0010. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | from urllib import request 10 | import datetime 11 | import re 12 | import os.path 13 | import requests 14 | 15 | 16 | def save_file(this_download_url, path): 17 | print("- - - - - - - - - - - - - - - - - - - - - - - - - - ") 18 | time1 = datetime.datetime.now() 19 | print(str(time1)[:-7], end=' ') 20 | if os.path.isfile(path): 21 | file_size = os.path.getsize(path) / 1024 / 1024 22 | print("File " + path + " (" + str(file_size) + "Mb) already exists.") 23 | return 24 | else: 25 | print("Downloading " + path + "...") 26 | r = requests.get(this_download_url, stream=True) 27 | with open(path.encode('utf-8'), "wb") as code: 28 | code.write(r.content) 29 | time2 = datetime.datetime.now() 30 | print(str(time2)[:-7], end=' ') 31 | print(path + " Done.") 32 | use_time = time2 - time1 33 | print("Time used: " + str(use_time)[:-7] + ", ", end=' ') 34 | file_size = os.path.getsize(path) / 1024 / 1024 35 | print( 36 | "File size: " + str(file_size) + " MB, Speed: " + str(file_size / (use_time.total_seconds()))[:4] + "MB/s") 37 | 38 | 39 | def download_url(website_url): 40 | fuckyou_header = { 41 | 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} 42 | req = request.Request(website_url, headers=fuckyou_header) 43 | content = request.urlopen(req).read() 44 | while len(content) < 100: 45 | print("try again...") 46 | content = request.urlopen(req).read() 47 | print("Web page all length:" + str(len(content))) 48 | 49 | pattern = re.compile(r"http://m4.26ts.com/[.0-9-a-zA-Z]*.mp4") 50 | match = pattern.search(str(content)) 51 | 52 | if match: 53 | the_url = match.group() 54 | save_file(the_url, the_url[19:]) 55 | else: 56 | print("No video found.") 57 | 58 | 59 | urls = ["http://www.46ek.com/view/22133.html", ] 60 | count = 0 61 | print(len(urls), end=' ') 62 | print(" videos to download...") 63 | for i in urls: 64 | count += 1 65 | print(count) 66 | download_url(i) 67 | print("All done") 68 | -------------------------------------------------------------------------------- /other_tools/urllib_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/01/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | import random 7 | from urllib import request 8 | 9 | __author__ = "TaoYuan" 10 | 11 | 12 | headers = { 13 | 'referer': 'http://blog.csdn.net/', 14 | 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 ' 15 | 'Safari/537.36 ' 16 | } 17 | 18 | 19 | def request_url(times, urls, headers): 20 | url = urls[random.randint(0, len(urls) - 1)] 21 | req = request.Request(url, headers=headers) 22 | request.urlopen(req) 23 | print("访问:{}次,本次访问:{}".format(times, url)) 24 | 25 | 26 | i = 0 27 | while True: 28 | i += 1 29 | urls = [ 30 | "http://blog.csdn.net/lftaoyuan/article/details/79085052", 31 | "http://blog.csdn.net/lftaoyuan/article/details/78563249", 32 | "http://blog.csdn.net/lftaoyuan/article/details/78549161", 33 | "http://blog.csdn.net/lftaoyuan/article/details/62234971", 34 | ] 35 | request_url(i, urls, headers) -------------------------------------------------------------------------------- /other_tools/virtualenv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | 顾名思义,虚拟环境 9 | http://blog.csdn.net/lftaoyuan/article/details/78618091 10 | """ -------------------------------------------------------------------------------- /requests_demo/requests_demo_01.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/3/23 0023. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | 7 | # 按关键词爬取头条的图片(因为头条比较友好) 8 | 9 | 10 | import os 11 | import requests 12 | 13 | # 默认地址本文件同级目录下新建img,可参考base_demo包的test28_path模块进行修改 14 | save_path = os.path.abspath(os.path.join(os.getcwd(), "img")) 15 | 16 | 17 | # 关键词 18 | kw = '' 19 | 20 | if not os.path.exists(save_path): 21 | os.mkdir(save_path) 22 | 23 | while True: 24 | 25 | kw = input('请输入关键字:') 26 | 27 | # 范围个数 28 | for x in range(0, 100, 20): 29 | url = 'https://www.toutiao.com/search_content/?offset=' + str(x)\ 30 | + '&format=json&keyword=%s&autoload=true&count=20&cur_tab=3&from=gallery' % kw 31 | response = requests.get(url) 32 | data = response.json()['data'] 33 | if not data: 34 | print('down!') 35 | break 36 | 37 | for atlas in data: 38 | # 创建目录 39 | title = atlas['title'] 40 | if title not in save_path: # 防止文件名已经存在 41 | os.mkdir(os.path.join(save_path, title)) 42 | k = 1 # 记录下载的图片数 43 | path = os.path.join(save_path, title) 44 | # 转进图片目录 45 | os.chdir(path) 46 | for image in atlas['image_list']: 47 | image_url = image['url'].replace('list', 'large') # 改个链接获取大的图片 48 | atlas = requests.get('http:' + image_url).content 49 | with open(str(k) + '.jpg', 'wb') as f: # 把图片写入文件内 50 | f.write(atlas) 51 | k += 1 52 | # 转出图片目录 53 | os.chdir(save_path) 54 | -------------------------------------------------------------------------------- /requests_demo/requests_demo_sample.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2018/2/2 0002. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | import requests 7 | 8 | with open("test.html", "wb") as code: 9 | code.write(requests.get("http://www.baidu.com/").content) 10 | -------------------------------------------------------------------------------- /static/FlaskDemo.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from flask import Flask 3 | 4 | app = Flask(__name__) 5 | 6 | 7 | @app.route('/get/taoyuan') 8 | def hello_world(): 9 | return "Hello World!" 10 | 11 | 12 | if __name__ == '__main__': 13 | app.run() 14 | -------------------------------------------------------------------------------- /static/location_file_server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | 9 | # 本地文件服务器 10 | 1. cmd到文件目录下 11 | 2. python -m http.server 80 (python2使用 python -m SimpleHTTPServer 8080) 12 | 3. 可以打开浏览器访问了,默认80不需要输入端口号 13 | 4. your IP(127.0.0.1 or localhost) 14 | """ 15 | 16 | 17 | -------------------------------------------------------------------------------- /static/yield_demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/27 0027. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | def addlist(alist): 10 | for i in alist: 11 | yield i + 1 12 | 13 | 14 | alist = [1, 2, 3, 4] 15 | for x in addlist(alist): 16 | print(x) 17 | 18 | print("--------------") 19 | 20 | 21 | def h(): 22 | print('study yield') 23 | yield 5 24 | print('go on!') 25 | 26 | 27 | c = h() 28 | h_d1 = next(c) # study yield 29 | c.close() 30 | # h_d2 = next(c) 31 | """ 32 | study yield 33 | go on! 34 | Traceback (most recent call last): 35 | File "D:/idea/workspace/pythonSpace/PythonDemo/static/yield_demo.py", line 35, in 36 | h_d2 = next(c) 37 | StopIteration 38 | """ 39 | 40 | print("--------------") 41 | 42 | 43 | def s(): 44 | print('study yield') 45 | m = yield 5 46 | print(m) 47 | d = yield 16 48 | print('go on!') 49 | 50 | 51 | c = s() 52 | s_d1 = next(c) # 相当于send(None) 53 | s_d2 = c.send('Fighting!') # (yield 5)表达式被赋予了'Fighting!' 54 | print('My Birth Day:', s_d1, '.', s_d2) 55 | """ 56 | study yield 57 | Fighting! 58 | My Birth Day: 5 . 16 59 | """ -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/5 0005. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 -------------------------------------------------------------------------------- /test/test01_unittest01.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/5 0005. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | class Student(object): 10 | def __init__(self, name, gender): 11 | self.name = name 12 | self.__gender = gender 13 | 14 | def get_gender(self): 15 | return self.__gender 16 | 17 | def set_gender(self, gender): 18 | if gender.__str__() != 'male' and gender.__str__() != 'female': 19 | raise ValueError('wrong') 20 | else: 21 | self.__gender = gender 22 | 23 | 24 | # 测试: 25 | bart = Student('Bart', 'male') 26 | if bart.get_gender() != 'male': 27 | print('测试失败1!') 28 | else: 29 | bart.set_gender('enen') 30 | if bart.get_gender() != 'female': 31 | print('测试失败2!') 32 | else: 33 | print('测试成功!') 34 | -------------------------------------------------------------------------------- /test/test02_unittest02.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/5 0005. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import unittest 8 | from error_and_debug.demo5_mydict import Dict 9 | 10 | 11 | # 编写单元测试时,我们需要编写一个测试类,从unittest.TestCase继承。 12 | class TestDict(unittest.TestCase): 13 | def setUp(self): 14 | print('setUp...') 15 | 16 | def tearDown(self): 17 | print('tearDown...') 18 | 19 | def test_init(self): 20 | d = Dict(a=1, b='test') 21 | self.assertEqual(d.a, 1) 22 | self.assertEqual(d.b, 'test') 23 | self.assertTrue(isinstance(d, dict)) 24 | 25 | # 以test开头的方法就是测试方法,不以test开头的方法不被认为是测试方法,测试的时候不会被执行。 26 | def test_key(self): 27 | d = Dict() 28 | d['key'] = 'value' 29 | self.assertEqual(d.key, 'value') 30 | 31 | def test_attr(self): 32 | d = Dict() 33 | d.key = 'value' 34 | self.assertTrue('key' in d) 35 | self.assertEqual(d['key'], 'value') 36 | 37 | def test_keyerror(self): 38 | d = Dict() 39 | with self.assertRaises(KeyError): 40 | value = d['empty'] 41 | 42 | def test_attrerror(self): 43 | d = Dict() 44 | with self.assertRaises(AttributeError): 45 | value = d.empty 46 | 47 | def test_isequeals(self): 48 | self.assertEqual(abs(-1), 1) 49 | 50 | 51 | if __name__ == '__main__': 52 | TestDict.setUp() 53 | unittest.main() 54 | -------------------------------------------------------------------------------- /test/test03_path.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/7 0007. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import os 8 | 9 | 10 | # 写法1 11 | # try: 12 | # f = open(os.path.abspath(os.path.join(os.getcwd(), "../work/test.txt")), "r") 13 | # print(f.read()) 14 | # finally: 15 | # if f: 16 | # f.close() 17 | 18 | # 写法2 19 | # with open(os.path.abspath(os.path.join(os.getcwd(), "../work/test.txt")), "r") as f: 20 | # print(f.read()) 21 | 22 | # 写法3(推荐) 23 | # with open(os.path.abspath(os.path.join(os.getcwd(), "../work/test.txt")), "r") as f: 24 | # for line in f.readlines(): 25 | # print(line.strip()) # 把末尾的'\n'删掉 26 | 27 | 28 | def return_sum( a, b): 29 | __a = int(a) 30 | __b = int(b) 31 | return __a + __b 32 | 33 | 34 | if __name__ == '__main__': 35 | print(return_sum(1, 2)) 36 | 37 | -------------------------------------------------------------------------------- /test/test04_game.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/8 0008. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | background_image_filename = 'C:\\Users\\Administrator\\Desktop\\image.png' 9 | mouse_image_filename = 'C:\\Users\\Administrator\\Desktop\\123.png' 10 | # 指定图像文件名称 11 | 12 | import pygame 13 | # 导入pygame库 14 | from pygame.locals import * 15 | # 导入一些常用的函数和常量 16 | from sys import exit 17 | 18 | # 向sys模块借一个exit函数用来退出程序 19 | 20 | pygame.init() 21 | # 初始化pygame,为使用硬件做准备 22 | 23 | screen = pygame.display.set_mode((640, 480), 0, 32) 24 | # 创建了一个窗口 25 | pygame.display.set_caption("Hello, World!") 26 | # 设置窗口标题 27 | 28 | background = pygame.image.load(background_image_filename).convert() 29 | mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha() 30 | # 加载并转换图像 31 | 32 | while True: 33 | # 游戏主循环 34 | 35 | for event in pygame.event.get(): 36 | if event.type == QUIT: 37 | # 接收到退出事件后退出程序 38 | exit() 39 | 40 | screen.blit(background, (0, 0)) 41 | # 将背景图画上去 42 | 43 | x, y = pygame.mouse.get_pos() 44 | # 获得鼠标位置 45 | x -= mouse_cursor.get_width() / 2 46 | y -= mouse_cursor.get_height() / 2 47 | # 计算光标的左上角位置 48 | screen.blit(mouse_cursor, (x, y)) 49 | # 把光标画上去 50 | 51 | pygame.display.update() 52 | # 刷新一下画面 53 | -------------------------------------------------------------------------------- /test/test05_closure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | def count(): 5 | fs = [] 6 | print("come in ") 7 | for i in range(1, 5): 8 | print("create f%s" % i) 9 | def f(): 10 | return i * i 11 | 12 | fs.append(f) 13 | return fs 14 | 15 | f1, f2, f3, f4 = count() 16 | print(f1(), f2(), f3(), f4()) 17 | 18 | 19 | # def count1(): 20 | # fs = [] 21 | # for i in range(1, 4): 22 | # def f(j): 23 | # def g(): 24 | # return j * j 25 | # return g 26 | # fs.append(f(i)) # �˲��踳ֵ 27 | # return fs 28 | # 29 | # f1, f2, f3 = count1() 30 | # print(f1(), f2(), f3()) 31 | 32 | 33 | # def count2(): 34 | # def f(j): 35 | # def g(): 36 | # return j * j 37 | # 38 | # return g 39 | # 40 | # fs = [] 41 | # for i in range(1, 4): 42 | # fs.append(f(i)) # f(i)���̱�ִ�У����i�ĵ�ǰֵ������f() 43 | # return fs 44 | # 45 | # 46 | # f1, f2, f3 = count2() 47 | # print(f1(), f2(), f3()) 48 | -------------------------------------------------------------------------------- /test/test06_aes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import sys 8 | from Crypto.Cipher import AES 9 | from binascii import b2a_hex, a2b_hex 10 | 11 | # class prpcrypt(): 12 | # def __init__(self, key): 13 | # self.key = key 14 | # self.mode = AES.MODE_CBC 15 | 16 | # #加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 17 | # def encrypt(self, text): 18 | # cryptor = AES.new(self.key, self.mode, self.key) 19 | # #这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用 20 | # length = 16 21 | # count = len(text) 22 | # if(count % length != 0) : 23 | # add = length - (count % length) 24 | # else: 25 | # add = 0 26 | # text = text + ('\0' * add) 27 | # self.ciphertext = cryptor.encrypt(text) 28 | # #因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 29 | # #所以这里统一把加密后的字符串转化为16进制字符串 30 | # return b2a_hex(self.ciphertext) 31 | 32 | # #解密后,去掉补足的空格用strip() 去掉 33 | # def decrypt(self, text): 34 | # cryptor = AES.new(self.key, self.mode, self.key) 35 | # plain_text = cryptor.decrypt(a2b_hex(text)) 36 | # return plain_text.rstrip('\0') 37 | 38 | # if __name__ == '__main__': 39 | # pc = prpcrypt('keyskeyskeyskeys') #初始化密钥 40 | # e = pc.encrypt("0123456789ABCDEF") 41 | # d = pc.decrypt(e) 42 | # print(e, d) 43 | # e = pc.encrypt("00000000000000000000000000") 44 | # d = pc.decrypt(e) 45 | # print(e, d) 46 | key = 'keyskeyskeyskeys' 47 | mode = AES.MODE_CBC 48 | 49 | cryptor = AES.new(key, mode, key) 50 | print(b2a_hex(cryptor.encrypt("abcdef"))) 51 | -------------------------------------------------------------------------------- /test/test07.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-12-17 21:48:54 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : https://github.com/seeways or http://blog.csdn.net/lftaoyuan 6 | # @Version : $Id$ 7 | 8 | 9 | # def a(*x): 10 | # print(x) 11 | # if len(x)<1: 12 | # raise TabError('1') 13 | # res = 1 14 | # for i in x: 15 | # res = res * i 16 | # return res 17 | # 18 | # 19 | # b = a(1, 2, 3) 20 | # print(b) 21 | 22 | l = 1, 2, 3, 10, -5 23 | print(min(l)) -------------------------------------------------------------------------------- /test/test08_sort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/20 0020. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | 8 | 9 | list1 = [7, -8, 5, 4, 0, -2, -5] 10 | 11 | result1 = sorted(list1) # 从小到大 12 | result2 = sorted(list1, key=lambda x: (x < 0, abs(x))) # 先排正负,再拍大小 13 | result3 = sorted(list1, key=lambda x: (x < 0)) # 从大到小 14 | 15 | print(result1) 16 | print(result2) 17 | print(result3) 18 | """ 19 | [-8, -5, -2, 0, 4, 5, 7] 20 | [0, 4, 5, 7, -2, -5, -8] 21 | [7, 5, 4, 0, -8, -2, -5] 22 | """ -------------------------------------------------------------------------------- /web/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 -------------------------------------------------------------------------------- /web/flask_demo_base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | http://flask.pocoo.org/ 9 | 10 | sample flask demo 11 | 12 | app.run() 13 | http://127.0.0.1:5000/ 14 | 15 | app.run("", 8000) 16 | http://localhost:8000/ 17 | """ 18 | from flask import Flask 19 | 20 | app = Flask(__name__) 21 | 22 | 23 | @app.route("/") 24 | def hello(): 25 | return "Hello World!" 26 | 27 | 28 | # host=None, port=None, debug=None, **options 29 | app.run() 30 | -------------------------------------------------------------------------------- /web/flask_demo_login.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | 写一个app.py,处理3个URL,分别是: 9 | 10 | GET /:首页,返回Home; 11 | 12 | GET /signin:登录页,显示登录表单; 13 | 14 | POST /signin:处理登录表单,显示登录结果。 15 | 16 | 注意噢,同一个URL/signin分别有GET和POST两种请求,映射到两个处理函数中。 17 | 18 | """ 19 | from flask import Flask, request 20 | 21 | app = Flask(__name__) 22 | 23 | 24 | @app.route("/", methods=["GET", "POST"]) 25 | def home(): 26 | return "

HOME

" 27 | 28 | 29 | @app.route("/sign_in", methods=["GET"]) 30 | def sign_in_form(): 31 | return""" 32 |
33 |

用户名:

34 |

密 码:

35 |

36 |
""" 37 | 38 | 39 | @app.route("/sign_in", methods=["POST"]) 40 | def sign_in(): 41 | username = request.form["username"] 42 | password = request.form["password"] 43 | if username == "admin" and password == "123456": 44 | return "

Hi! {}, Welcome To Here!

".format(username) 45 | return "

Bad username or password!

" 46 | 47 | 48 | if __name__ == '__main__': 49 | app.run() 50 | -------------------------------------------------------------------------------- /web/flask_demo_mvc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | MVC Demo 9 | 10 | Flask通过render_template()函数来实现模板的渲染。 11 | 和Web框架类似,Python的模板也有很多种。 12 | Flask默认支持的模板是jinja2 13 | """ 14 | from flask import Flask, request, render_template 15 | 16 | app = Flask(__name__) 17 | 18 | 19 | @app.route("/", methods=["GET", "POST"]) 20 | def home(): 21 | return render_template("web_home.html") 22 | 23 | 24 | @app.route("/sign_in", methods=["GET"]) 25 | def sign_in_form(): 26 | return render_template("web_login.html") 27 | 28 | 29 | @app.route("/sign_in", methods=["POST"]) 30 | def sign_in(): 31 | username = request.form["username"] 32 | password = request.form["password"] 33 | if username == "admin" and password == "123456": 34 | return render_template("web_ok.html", username=username) 35 | return render_template("web_login.html", message="Bad username or password", username=username) 36 | 37 | 38 | if __name__ == '__main__': 39 | app.run() 40 | -------------------------------------------------------------------------------- /web/my_res/web_form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | $Title$ 6 | 7 | 8 | $END$ 9 | 10 | -------------------------------------------------------------------------------- /web/my_res/web_tcp_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/web/my_res/web_tcp_demo.png -------------------------------------------------------------------------------- /web/my_res/web_udp_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/web/my_res/web_udp_demo.png -------------------------------------------------------------------------------- /web/my_res/wsgi_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/web/my_res/wsgi_01.png -------------------------------------------------------------------------------- /web/my_res/wsgi_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/web/my_res/wsgi_02.png -------------------------------------------------------------------------------- /web/templates/web_home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Home 8 | 9 | 10 | 11 | 12 | 13 |

Hello World!

14 | 15 | -------------------------------------------------------------------------------- /web/templates/web_login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Login 7 | 8 | 9 | {% if message %} 10 |

{{ message }}

11 | {% endif %} 12 |
13 | Please Login 14 | username:

15 | password:

16 |

17 |
18 | 19 | 20 | -------------------------------------------------------------------------------- /web/templates/web_ok.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Welcome {{ username }} 7 | 8 | 9 |

Hi {{ username }} ! Welcome To Here!

10 | 11 | -------------------------------------------------------------------------------- /web/web_tcp_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import socket 8 | 9 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 10 | # 建立连接: 11 | s.connect(('127.0.0.1', 9999)) 12 | # 接收欢迎消息: 13 | print(s.recv(1024).decode('utf-8')) 14 | for data in [b'Michael', b'Tracy', b'Sarah']: 15 | # 发送数据: 16 | s.send(data) 17 | print(s.recv(1024).decode('utf-8')) 18 | s.send(b'exit') 19 | s.close() 20 | -------------------------------------------------------------------------------- /web/web_tcp_demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/19 0019. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import socket 8 | 9 | # 用ipv4创建一个面向流的socket对象,下面为参数及默认值 10 | # self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None 11 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0, None) 12 | # 建立连接 address = (host, port) 13 | s.connect(('www.sina.com.cn', 80)) 14 | # 发送数据: 15 | s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n') 16 | # 接收数据: 17 | buffer = [] 18 | while True: 19 | # 从socket接收缓冲区字节大小:1k 20 | d = s.recv(1024) 21 | if d: 22 | buffer.append(d) 23 | else: 24 | break 25 | data = b''.join(buffer) 26 | # 关闭连接: 27 | s.close() 28 | # 接收到的数据包括HTTP头和网页本身 29 | # 我们只需要把HTTP头和网页分离一下,把HTTP头打印出来,网页内容保存到文件 30 | header, html = data.split(b'\r\n\r\n', 1) 31 | print(header.decode('utf-8')) 32 | # 把接收的数据写入文件: 33 | with open('my_res/sina.html', 'wb') as f: 34 | f.write(html) 35 | 36 | """ 37 | HTTP/1.1 200 OK 38 | Server: nginx 39 | Date: Tue, 19 Dec 2017 10:18:31 GMT 40 | Content-Type: text/html 41 | Content-Length: 604543 42 | Connection: close 43 | Last-Modified: Tue, 19 Dec 2017 10:18:17 GMT 44 | Vary: Accept-Encoding 45 | Expires: Tue, 19 Dec 2017 10:19:29 GMT 46 | Cache-Control: max-age=60 47 | X-Powered-By: shci_v1.03 48 | Age: 2 49 | Via: http/1.1 ctc.ningbo.ha2ts4.97 (ApacheTrafficServer/6.2.1 [cHs f ]), http/1.1 ctc.xiamen.ha2ts4.41 (ApacheTrafficServer/6.2.1 [cHs f ]) 50 | X-Via-Edge: 1513678711708779d11da3cd64cde57ebfc32 51 | X-Cache: HIT.41 52 | X-Via-CDN: f=edge,s=ctc.xiamen.ha2ts4.42.nb.sinaedge.com,c=218.17.157.119;f=Edge,s=ctc.xiamen.ha2ts4.41,c=222.76.214.42 53 | """ -------------------------------------------------------------------------------- /web/web_tcp_server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/20 0020. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | 7 | import socket 8 | import threading 9 | import time 10 | 11 | # 创建一个基于IPv4和TCP协议的Socket 12 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 | # 然后要绑定监听的地址和端口,服务器可能有多块网卡,可以绑定到某一块网卡的IP地址上 14 | # 也可以用0.0.0.0绑定到所有的网络地址,还可以用127.0.0.1绑定到本机地址,只有本地才能访问 15 | # 端口号需要预先指定,小于1024的端口号必须要有管理员权限才能绑定 16 | # 监听端口: 17 | s.bind(('127.0.0.1', 9999)) 18 | # 紧接着,调用listen()方法开始监听端口,传入的参数指定等待连接的最大数量: 19 | s.listen(5) 20 | print('Waiting for connection...') 21 | 22 | 23 | # 每个连接都必须创建新线程(或进程)来处理,否则,单线程在处理连接的过程中,无法接受其他客户端的连接 24 | def tcplink(sock, addr): 25 | print('Accept new connection from %s:%s...' % addr) 26 | sock.send(b'Welcome!') 27 | while True: 28 | data = sock.recv(1024) 29 | time.sleep(1) 30 | if not data or data.decode('utf-8') == 'exit': 31 | break 32 | sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8')) 33 | sock.close() 34 | print('Connection from %s:%s closed.' % addr) 35 | 36 | 37 | # 接下来,服务器程序通过一个永久循环来接受来自客户端的连接,accept()会等待并返回一个客户端的连接 38 | while True: 39 | # 接受一个新连接: 40 | sock, address = s.accept() 41 | # 创建新线程来处理TCP连接: 42 | t = threading.Thread(target=tcplink, args=(sock, address)) 43 | t.start() 44 | -------------------------------------------------------------------------------- /web/web_udp_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/20 0020. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import socket 8 | 9 | """ 10 | 客户端使用UDP时,首先仍然创建基于UDP的Socket,然后,不需要调用connect(),直接通过sendto()给服务器发数据 11 | """ 12 | 13 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 14 | for data in [b'Michael', b'Tracy', b'Sarah']: 15 | # 发送数据: 16 | s.sendto(data, ('127.0.0.1', 9999)) 17 | # 接收数据: 18 | print(s.recv(1024).decode('utf-8')) 19 | s.close() -------------------------------------------------------------------------------- /web/web_udp_server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/20 0020. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import socket 8 | 9 | 10 | # 创建Socket时,socket.SOCK_DGRAM指定了这个Socket的类型是UDP 11 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 12 | # 绑定端口: 13 | s.bind(('127.0.0.1', 9999)) 14 | # 绑定端口和TCP一样,但是不需要调用listen()方法,而是直接接收来自任何客户端的数据 15 | print('Bind UDP on 9999...') 16 | # recvfrom()方法返回数据和客户端的地址与端口 17 | # 服务器收到数据后,直接调用sendto()就可以把数据用UDP发给客户端 18 | while True: 19 | # 接收数据: 20 | data, addr = s.recvfrom(1024) 21 | print('Received from %s:%s.' % addr) 22 | s.sendto(b'Hello, %s!' % data, addr) 23 | 24 | -------------------------------------------------------------------------------- /web/web_wsgi_demo1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | Web服务器网关接口 9 | WSGI:Web Server Gateway Interface 10 | 11 | Web应用的本质就是: 12 | 13 | 1. 浏览器发送一个HTTP请求; 14 | 2. 服务器收到请求,生成一个HTML文档; 15 | 3. 服务器把HTML文档作为HTTP响应的Body发送给浏览器; 16 | 4. 浏览器收到HTTP响应,从HTTP Body取出HTML文档并显示。 17 | 18 | WSGI接口定义非常简单,它只要求Web开发者实现一个函数,就可以响应HTTP请求 19 | """ 20 | 21 | 22 | # 上面的application()函数就是符合WSGI标准的一个HTTP处理函数,它接收两个参数: 23 | 24 | # environ:一个包含所有HTTP请求信息的dict对象; 25 | # start_response:一个发送HTTP响应的函数。 26 | def application(environ, start_response): 27 | start_response("200 OK", [("Content-Type", "text/html")]) # 发送响应的header,并且只发送一次 28 | # 从environ里读取PATH_INFO,这样可以显示更加动态的内容 29 | body = "

Hello {}, Welcome come here!

".format(environ["PATH_INFO"][1:] or "web") 30 | return [body.encode("utf-8")] # 请求体Body 31 | 32 | # 有了WSGI,我们关心的就是如何从environ这个dict对象拿到HTTP请求信息,然后构造HTML,通过start_response()发送Header,最后返回Body。 33 | # 整个application()函数本身没有涉及到任何解析HTTP的部分,也就是说,底层代码不需要我们自己编写,我们只负责在更高层次上考虑如何响应请求就可以了 34 | # 但是, application()函数必须由WSGI服务器来调用 35 | 36 | # Python内置了一个简单的WSGI服务器,叫wsgiref 37 | 38 | """ 39 | 小结 40 | 41 | 无论多么复杂的Web应用程序,入口都是一个WSGI处理函数。 42 | HTTP请求的所有输入信息都可以通过environ获得 43 | HTTP响应的输出都可以通过start_response()加上函数返回值作为Body。 44 | 45 | 复杂的Web应用程序,光靠一个WSGI函数来处理还是太底层了 46 | 我们需要在WSGI之上再抽象出Web框架,进一步简化Web开发。 47 | """ -------------------------------------------------------------------------------- /web/web_wsgi_demo_server1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/26 0026. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | """ 8 | server 9 | 负责启动WSGI服务器,加载application 10 | """ 11 | from wsgiref.simple_server import make_server 12 | from web_wsgi_demo1 import application 13 | 14 | 15 | # 创建一个服务器,IP为空,端口8000,处理函数为application 16 | httpd = make_server("", 8000, application) 17 | print("serving http on prot 8000...") 18 | # 监听http请求 19 | httpd.serve_forever() 20 | -------------------------------------------------------------------------------- /web_spider/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/21 0021 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 -------------------------------------------------------------------------------- /web_spider/demo1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/21 0021 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | 8 | import urllib.request 9 | 10 | keywd = '矮大紧' 11 | url = 'http://www.baidu.com/s?wd=' 12 | keywd_code = urllib.request.quote(keywd) 13 | url_all = url + keywd_code 14 | request = urllib.request.Request(url_all) 15 | data = urllib.request.urlopen(request).read() 16 | filename = 'C:\\Users\\Administrator\\Desktop\\5.html' 17 | file = open(filename, 'wb') # 打开文件 18 | file.write(data) # 写入文件 19 | file.close() # 关闭文件 20 | -------------------------------------------------------------------------------- /web_spider/get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/21 0021 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | 8 | import urllib.request 9 | from test05_custom_class import Chain 10 | 11 | 12 | # 动态拼接url 13 | url = "{}{}".format('http://127.0.0.1:5000', Chain().get.taoyuan) 14 | 15 | request = urllib.request.Request(url) 16 | response = urllib.request.urlopen(request) 17 | if response.getcode() != 200: 18 | print("None!") 19 | else: 20 | html = response.read() 21 | # 如果返回结果不为空 22 | if html is not None: 23 | # html = html.decode("utf-8") 24 | filename = 'C:\\Users\\Administrator\\Desktop\\test.html' 25 | file = open(filename, 'wb') 26 | file.write(html) 27 | file.close() 28 | print("--------页面信息----------") 29 | print(html) 30 | 31 | else: 32 | print("Maybe The Program is Error!") 33 | 34 | # 头信息 35 | print("--------头信息----------") 36 | print(response.info()) 37 | -------------------------------------------------------------------------------- /work/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seeways/PythonDemo/c95dc4807553701bca410f3a74a5ef8fdcde3c54/work/__init__.py -------------------------------------------------------------------------------- /work/auto_increment_student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/1 0001. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加: 8 | 9 | 10 | class Student(object): 11 | count = 0 12 | 13 | def __init__(self, name): 14 | self.name = name 15 | Student.count += 1 16 | print(self.count) 17 | 18 | 19 | # 测试: 20 | if Student.count != 0: 21 | print('测试失败!') 22 | else: 23 | bart = Student('Bart') 24 | if Student.count != 1: 25 | print('测试失败!') 26 | else: 27 | lisa = Student('Bart') 28 | if Student.count != 2: 29 | print('测试失败!') 30 | else: 31 | print('Students:', Student.count) 32 | print('测试通过!') 33 | -------------------------------------------------------------------------------- /work/closure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-27 20:12:56 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # @des : 利用闭包返回一个计数器函数,每次调用它返回递增整数: 8 | 9 | 10 | def createCounter(): 11 | def add_nums(): # 2. 添加计数 12 | n = 0 13 | while True: 14 | n = n + 1 15 | yield n 16 | 17 | y = add_nums() 18 | 19 | def counter(): # 1. 首先调用此函数 20 | return next(y) # 3. 迭代计数 21 | 22 | return counter 23 | 24 | 25 | if __name__ == '__main__': 26 | # 测试: 27 | counterA = createCounter() 28 | print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 29 | counterB = createCounter() 30 | if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: 31 | print('测试通过!') 32 | else: 33 | print('测试失败!') 34 | -------------------------------------------------------------------------------- /work/decorator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-28 17:16:24 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # @des: 请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间: 8 | import functools 9 | import time 10 | 11 | # wrok 1 12 | def metric(fn): 13 | def wrapper(*args, **kw): 14 | start_time = time.time() 15 | print('{0} executed in {1} ms'.format(fn.__name__, time.time() - start_time)) 16 | return fn(*args, **kw) 17 | return wrapper 18 | 19 | 20 | # work 2 21 | def log(text=None): 22 | start_time = time.time() 23 | print("begin call:", round(start_time)) 24 | def decorate(func): 25 | @functools.wraps(func) 26 | def wrapper(*args, **kw): 27 | return func(*args, **kw), print("end call:{0} \n spend time: {1} s".format(round(time.time()), round(time.time() - start_time))) 28 | return wrapper 29 | return (decorate, print("text:%s" % text ))[0] if text.__str__() == text else decorate(text) 30 | 31 | 32 | # 测试 33 | @metric 34 | def fast(x, y): 35 | time.sleep(0.0012) 36 | return x + y 37 | 38 | 39 | @metric 40 | def slow(x, y, z): 41 | time.sleep(0.1234) 42 | return x * y * z 43 | 44 | 45 | f = fast(11, 22) 46 | s = slow(11, 22, 33) 47 | if f != 33: 48 | print('测试失败!') 49 | elif s != 7986: 50 | print('测试失败!') 51 | 52 | print('-------work2-------') 53 | 54 | 55 | @log 56 | def test1(): 57 | time.sleep(2) 58 | 59 | 60 | @log('这里是参数') 61 | def test2(): 62 | time.sleep(3) 63 | 64 | 65 | test1() 66 | 67 | test2() 68 | -------------------------------------------------------------------------------- /work/exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/4 0004. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | from functools import reduce 8 | 9 | 10 | def str2num(s): 11 | try: 12 | n = int(s) 13 | except ValueError as e: 14 | print("Not Integer,Will Be Convert To Float:", e) 15 | n = float(s) 16 | return n 17 | 18 | 19 | def calc(exp): 20 | ss = exp.split('+') 21 | ns = map(str2num, ss) 22 | return reduce(lambda acc, x: acc + x, ns) 23 | 24 | 25 | def main(): 26 | r = calc('100 + 200 + 345') 27 | print('100 + 200 + 345 =', r) 28 | print("---------------------------") 29 | r = calc('99 + 88 + 7.6') 30 | print('99 + 88 + 7.6 =', r) 31 | 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /work/file_io.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/23 0023 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | 8 | 9 | def wt_file(): # 写文件 10 | with open("test.txt", "wt") as out_file: 11 | out_file.write("test\n test2 \n\n test4") 12 | 13 | 14 | def rd_file(): # 读文件 15 | with open("test.txt", "rt") as in_file: 16 | text = in_file.read() 17 | print(text) 18 | 19 | 20 | if __name__ == '__main__': 21 | # 卸载本文件同级目录下 22 | wt_file() 23 | rd_file() 24 | -------------------------------------------------------------------------------- /work/findMinAndMax.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-20 17:02:00 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | from collections import Iterable 8 | 9 | 10 | def findMinAndMax(L): 11 | if not isinstance(L, Iterable): 12 | raise TypeError("L not Iterable!") 13 | 14 | if 0 == len(L): 15 | return None, None 16 | 17 | min_num = L[0] 18 | max_num = L[0] 19 | for i in L: 20 | if i < min_num: 21 | min_num = i 22 | elif i > max_num: 23 | max_num = i 24 | return min_num, max_num 25 | 26 | 27 | if __name__ == '__main__': 28 | # 测试 29 | if findMinAndMax([]) != (None, None): 30 | print('测试失败1!') 31 | elif findMinAndMax([7]) != (7, 7): 32 | print('测试失败2!') 33 | elif findMinAndMax([7, 1]) != (1, 7): 34 | print('测试失败3!') 35 | elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9): 36 | print('测试失败4!') 37 | elif findMinAndMax((1, 2, 3, 4, 5, 6)) != (1, 6): 38 | print('测试失败5!') 39 | else: 40 | print('测试成功!') 41 | -------------------------------------------------------------------------------- /work/io_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/8 0008. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 1. 利用os模块编写一个能实现dir -l输出的程序。 8 | # 2. 编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。 9 | # V2.0 优化函数 10 | import os 11 | 12 | 13 | def dir_l(): 14 | print(os.listdir('.')) 15 | 16 | 17 | """ 18 | root 当前目录路径 19 | dirs 当前路径下所有子目录 20 | files 当前路径下所有非目录子文件 21 | """ 22 | 23 | 24 | def get_files(file_name, dir_path=os.path.abspath(".")): 25 | for root, dirs, files in os.walk(dir_path): # 获取当前目录的所有子目录和文件 26 | for file_path in files: 27 | if file_name in file_path: 28 | print(os.path.join(root, file_path)) 29 | 30 | 31 | if __name__ == '__main__': 32 | # dir_l() # 我的理解是输出当前目录所有文件名 33 | get_files("test") # 我的理解是模糊匹配 34 | -------------------------------------------------------------------------------- /work/io_r_w.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/7 0007. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import os 8 | 9 | fpath = os.path.abspath(os.path.join(os.getcwd(), "../work/test.txt")) 10 | 11 | with open(fpath, 'r') as f: 12 | s = f.read() 13 | print(s) -------------------------------------------------------------------------------- /work/map_reduce.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/23 0023 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | from functools import reduce 8 | 9 | 10 | # print(str.upper()) # 把所有字符中的小写字母转换成大写字母 11 | # print(str.lower()) # 把所有字符中的大写字母转换成小写字母 12 | # print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写 13 | # print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写 14 | def normalize(name): # 首字母大写,其余小写 15 | return name.capitalize() 16 | 17 | 18 | def prod(L): # 求积 19 | return reduce(lambda x, y: x * y, L) 20 | 21 | 22 | def str2float(s): # 要求reduce和map 23 | def char2num(s): 24 | return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] 25 | 26 | n = s.index('.') 27 | return reduce(lambda x, y: x * 10 + y, map(char2num, s[:n] + s[n + 1:])) / (10 ** (len(s) - n - 1)) 28 | 29 | 30 | # def str2float(s): # 实际中 31 | # return float(s) 32 | 33 | 34 | if __name__ == '__main__': 35 | # 大小写转换测试: 36 | L1 = ['adam', 'LISA', 'barT'] 37 | L2 = list(map(normalize, L1)) 38 | print(L2) 39 | 40 | # 求乘积测试 41 | print('-' * 30) 42 | print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) 43 | if prod([3, 5, 7, 9]) == 945: 44 | print('测试成功!') 45 | else: 46 | print('测试失败!') 47 | 48 | # str 2 float 测试 49 | print('-' * 30) 50 | print('str2float(\'123.456\') =', str2float('123.456')) 51 | print('str2float(\'12345.6\') =', str2float('12345.6')) 52 | if abs(str2float('123.456') - 123.456) < 0.00001: 53 | print('测试成功!') 54 | else: 55 | print('测试失败!') 56 | -------------------------------------------------------------------------------- /work/palindrome.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/24 0024 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | # @des : 判断是否为回数 8 | 9 | 10 | def is_palindrome(n): 11 | return str(n) == str(n)[::-1] # 字符串倒过来如果==字符串,则为回数 12 | 13 | 14 | if __name__ == '__main__': 15 | # 测试: 16 | output = filter(is_palindrome, range(1, 1000)) 17 | print('1~1000:', list(output)) 18 | if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 19 | 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: 20 | print('测试成功!') 21 | else: 22 | print('测试失败!') 23 | -------------------------------------------------------------------------------- /work/screen.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/1 0001. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution: 8 | 9 | 10 | class Screen(object): 11 | @property 12 | def width(self): 13 | return self.__width 14 | 15 | @width.setter 16 | def width(self, width): 17 | if not isinstance(width, int): 18 | raise ValueError("must be integer!") 19 | elif width < 0: 20 | raise ValueError("Error Value:", width) 21 | else: 22 | self.__width = width 23 | 24 | @property 25 | def height(self): 26 | return self.__height 27 | 28 | @height.setter 29 | def height(self, height): 30 | if not isinstance(height, int): 31 | raise ValueError("must be integer!") 32 | elif height < 0: 33 | raise ValueError("Error Value:", height) 34 | else: 35 | self.__height = height 36 | 37 | @property 38 | def resolution(self): 39 | return self.__height * self.__width 40 | 41 | 42 | if __name__ == '__main__': 43 | # 测试: 44 | s = Screen() 45 | s.width = 1024 46 | s.height = 768 47 | print('resolution =', s.resolution) 48 | if s.resolution == 786432: 49 | print('测试通过!') 50 | else: 51 | print('测试失败!') 52 | -------------------------------------------------------------------------------- /work/serialize_and_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/8 0008. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import json 8 | 9 | """ 10 | ensure_ascii=True 11 | {"name": "\u5c0f\u660e", "age": 20} 12 | 13 | ensure_ascii=False 14 | {"name": "小明", "age": 20} 15 | """ 16 | obj = dict(name='小明', age=20) 17 | s = json.dumps(obj, ensure_ascii=True) 18 | 19 | print(s) 20 | -------------------------------------------------------------------------------- /work/student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017-11-30 17:54:54 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : $Id$ 7 | # @des : 请把下面的Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性 8 | 9 | 10 | class Student(object): 11 | def __init__(self, name, gender): 12 | self.name = name 13 | self.__gender = gender 14 | 15 | def get_gender(self): 16 | return self.__gender 17 | 18 | def set_gender(self, gender): 19 | if gender.__str__() == 'male' or gender.__str__() == 'female': 20 | self.__gender = gender 21 | else: 22 | raise ValueError('不男不女') 23 | 24 | 25 | if __name__ == '__main__': 26 | # 测试: 27 | bart = Student('Bart', 'male') 28 | if bart.get_gender() != 'male': 29 | print('测试失败!') 30 | else: 31 | bart.set_gender('female') 32 | if bart.get_gender() != 'female': 33 | print('测试失败!') 34 | else: 35 | try: 36 | bart.set_gender('人妖') 37 | print('测试失败!') 38 | except ValueError: 39 | print('测试成功!') 40 | -------------------------------------------------------------------------------- /work/unittest_student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/7 0007. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import unittest 8 | 9 | 10 | class Student(object): 11 | def __init__(self, name, score): 12 | self.name = name 13 | self.score = score 14 | 15 | def get_grade(self): 16 | if 60 > self.score >= 0: 17 | return "C" 18 | if 80 > self.score >= 60: 19 | return 'B' 20 | if 100 >= self.score >= 80: 21 | return 'A' 22 | raise ValueError("score error!") 23 | 24 | 25 | class TestStudent(unittest.TestCase): 26 | def test_80_to_100(self): 27 | s1 = Student('Bart', 80) 28 | s2 = Student('Lisa', 100) 29 | self.assertEqual(s1.get_grade(), 'A') 30 | self.assertEqual(s2.get_grade(), 'A') 31 | 32 | def test_60_to_80(self): 33 | s1 = Student('Bart', 60) 34 | s2 = Student('Lisa', 79) 35 | self.assertEqual(s1.get_grade(), 'B') 36 | self.assertEqual(s2.get_grade(), 'B') 37 | 38 | def test_0_to_60(self): 39 | s1 = Student('Bart', 0) 40 | s2 = Student('Lisa', 59) 41 | self.assertEqual(s1.get_grade(), 'C') 42 | self.assertEqual(s2.get_grade(), 'C') 43 | 44 | def test_invalid(self): 45 | s1 = Student('Bart', -1) 46 | s2 = Student('Lisa', 101) 47 | with self.assertRaises(ValueError): 48 | s1.get_grade() 49 | with self.assertRaises(ValueError): 50 | s2.get_grade() 51 | 52 | 53 | if __name__ == '__main__': 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /work/work_async_await.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/27 0027. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 用asyncio的异步网络连接来获取sina、sohu和163的网站首页 8 | # 异步获取sina、sohu和163的网站首页源码用新语法重写并运行。 9 | import asyncio 10 | 11 | 12 | async def wget(host): 13 | print("wget {}".format(host)) 14 | connect = asyncio.open_connection(host, 80) 15 | reader, writer = await connect 16 | header = 'GET / HTTP/1.0\r\nHost: {}\r\n\r\n'.format(host) 17 | writer.write(header.encode("utf-8")) 18 | await writer.drain() 19 | while True: 20 | line = await reader.readline() 21 | if line == b'\r\n': 22 | break 23 | print("{} header:{}".format(host, line.decode("utf-8").rstrip())) 24 | # Ignore the body, close the socket 25 | writer.close() 26 | 27 | 28 | loop = asyncio.get_event_loop() 29 | tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']] 30 | loop.run_until_complete(asyncio.wait(tasks)) 31 | loop.close() -------------------------------------------------------------------------------- /work/work_bmpinfo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/14 0014. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 请编写一个bmpinfo.py,可以检查任意文件是否是位图文件,如果是,打印出图片大小和颜色数 8 | import base64 9 | import struct 10 | 11 | bmp_data = base64.b64decode( 12 | 'Qk1oAgAAAAAAADYAAAAoAAAAHAAAAAoAAAABABAAAAAAADICAAASCwAAEgsAAAAAAAAAAAAA/3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9/AHwAfAB8AHwAfAB8AHwAfP9//3//fwB8AHwAfAB8/3//f/9/AHwAfAB8AHz/f/9//3//f/9//38AfAB8AHwAfAB8AHwAfAB8AHz/f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9//3//f/9/AHwAfP9//3//f/9//3//f/9//38AfAB8AHwAfAB8AHwAfP9//3//f/9/AHwAfP9//3//f/9//38AfAB8/3//f/9//3//f/9//3//fwB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9/AHz/f/9/AHwAfP9//38AfP9//3//f/9/AHwAfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfP9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfAB8AHz/fwB8AHwAfAB8AHwAfAB8AHz/f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//38AAA==') 13 | 14 | 15 | def bmp_info(data): 16 | img_info = struct.unpack_from('? and score<=? order by score", (str(low), str(high))) 35 | values = cursor.fetchall() 36 | print(values) 37 | finally: 38 | cursor.close() 39 | conn.close() 40 | return [x[1] for x in values] 41 | 42 | 43 | # 测试: 44 | assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95) 45 | assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80) 46 | assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100) 47 | 48 | print('Pass') 49 | -------------------------------------------------------------------------------- /work/work_doctest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/7 0007. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | import doctest 8 | 9 | 10 | def fact(n): 11 | """ 12 | Calculate 1*2*...*n 13 | 14 | >>> fact(1) 15 | 1 16 | >>> fact(10) 17 | 3628800 18 | >>> fact(-1) 19 | Traceback (most recent call last): 20 | ... 21 | ValueError 22 | """ 23 | if n < 1: 24 | raise ValueError() 25 | if n == 1: 26 | return 1 27 | return n * fact(n - 1) 28 | 29 | 30 | if __name__ == '__main__': 31 | 32 | doctest.testmod() 33 | -------------------------------------------------------------------------------- /work/work_hmac.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # work_md5_salt的salt改为标准的hmac算法,验证用户口令 8 | import hmac 9 | import random 10 | 11 | 12 | def hmac_md5(key, s): 13 | return hmac.new(key.encode('utf-8'), s.encode('utf-8')).hexdigest() # 默认md5 14 | 15 | 16 | class User(object): 17 | def __init__(self, username, password): 18 | self.username = username 19 | self.password = hmac_md5(username, password + create_salt(username)) 20 | 21 | 22 | def create_salt(username): 23 | salt = '' 24 | chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' 25 | len_chars = len(chars) - 1 26 | for i in range(5): 27 | # 每次从chars中随机取一位 28 | salt += chars[random.randint(0, len_chars)] 29 | if username in db: 30 | return salt_db[username] 31 | else: 32 | salt_db[username] = salt 33 | return salt_db[username] 34 | 35 | 36 | db = {} 37 | salt_db = {} 38 | 39 | 40 | def regist(username, password): 41 | if username in db: 42 | print("username existed!") 43 | else: 44 | db[username] = User(username, password) 45 | 46 | 47 | def login(username, password): 48 | user = db[username] 49 | return hmac_md5(username, password + create_salt(username)) == user.password 50 | 51 | 52 | if __name__ == '__main__': 53 | # register 54 | regist('michael', '123456') 55 | login('michael', '123456') 56 | regist('bob', 'abc999') 57 | regist('alice', 'alice2008') 58 | # login: 59 | assert login('michael', '123456') 60 | assert login('bob', 'abc999') 61 | assert login('alice', 'alice2008') 62 | assert not login('michael', '1234567') 63 | assert not login('bob', '123456') 64 | assert not login('alice', 'Alice2008') 65 | print('ok') 66 | -------------------------------------------------------------------------------- /work/work_html_parse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/18 0018. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 找一个网页,例如https://www.python.org/events/python-events/,用浏览器查看源码并复制 8 | # 尝试解析一下HTML,输出Python官网发布的会议时间、名称和地点。 9 | from urllib import request 10 | from bs4 import BeautifulSoup 11 | 12 | url = "https://www.python.org/events/python-events/" 13 | 14 | 15 | def crawl_page(path): 16 | return request.urlopen(url).read().decode("utf-8") 17 | 18 | 19 | def parse_web(data): 20 | soup = BeautifulSoup(data, "html.parser") 21 | conference_list = soup.find('ul', attrs={'class': 'list-recent-events menu'}) 22 | for li in conference_list.find_all("li"): 23 | print("meeting name:", li.find('h3', attrs={'class': 'event-title'}).getText()) # 名称 24 | print("time:", li.find('time').getText()) 25 | print("address:", li.find('span', attrs={"class": "event-location"}).getText()+"\n") 26 | 27 | 28 | if __name__ == '__main__': 29 | # print(crawl_page(url)) 30 | parse_web(crawl_page(url)) 31 | 32 | """ 33 | 结果 34 | meeting name: PyCascades 2018 35 | time: 22 Jan. – 24 Jan. 2018 36 | address: Granville Island Stage, 1585 Johnston St, Vancouver, BC V6H 3R9, Canada 37 | 38 | meeting name: PyCon Cameroon 2018 39 | time: 24 Jan. – 29 Jan. 2018 40 | address: Limbe, Cameroon 41 | 42 | meeting name: FOSDEM 2018 43 | time: 03 Feb. – 05 Feb. 2018 44 | address: ULB Campus du Solbosch, Av. F. D. Roosevelt 50, 1050 Bruxelles, Belgium 45 | 46 | meeting name: PyCon Pune 2018 47 | time: 08 Feb. – 12 Feb. 2018 48 | address: Pune, India 49 | 50 | meeting name: PyCon Colombia 2018 51 | time: 09 Feb. – 12 Feb. 2018 52 | address: Medellin, Colombia 53 | 54 | meeting name: PyTennessee 2018 55 | time: 10 Feb. – 12 Feb. 2018 56 | address: Nashville, TN, USA 57 | """ -------------------------------------------------------------------------------- /work/work_itertools.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 利用Python提供的itertools模块,我们来计算这个序列的前N项和 8 | import itertools 9 | 10 | 11 | def pi(N): 12 | """ 13 | step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ... 14 | step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1. for x in range(2 * N) if x % 2 15 | step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... itertools.cycle((4, -4)) 16 | step 4: 求和:sum() 17 | 感觉水平还是不行 18 | """ 19 | n = itertools.cycle((4, -4)) 20 | return sum((next(n) / x) for x in range(2 * N) if x % 2) 21 | 22 | 23 | # 测试: 24 | print(pi(10)) 25 | print(pi(100)) 26 | print(pi(1000)) 27 | print(pi(10000)) 28 | assert 3.04 < pi(10) < 3.05 29 | assert 3.13 < pi(100) < 3.14 30 | assert 3.140 < pi(1000) < 3.141 31 | assert 3.1414 < pi(10000) < 3.1415 32 | print('ok') 33 | -------------------------------------------------------------------------------- /work/work_md5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 根据用户输入的口令,计算出存储在数据库中的MD5口令 8 | import hashlib 9 | 10 | db = { 11 | 'michael': 'e10adc3949ba59abbe56e057f20f883e', 12 | 'bob': '878ef96e86145580c38c87f0410ad153', 13 | 'alice': '99b1c2188db85afee403b1536010c2c9' 14 | } 15 | 16 | 17 | def calc_md5(password): 18 | return hashlib.md5(password.encode('utf-8')).hexdigest() 19 | 20 | 21 | def login(user, password): 22 | if db[user] == calc_md5(password): 23 | return True 24 | else: 25 | return False 26 | 27 | 28 | # 测试: 29 | assert login('michael', '123456') 30 | assert login('bob', 'abc999') 31 | assert login('alice', 'alice2008') 32 | assert not login('michael', '1234567') 33 | assert not login('bob', '123456') 34 | assert not login('alice', 'Alice2008') 35 | print('ok') 36 | -------------------------------------------------------------------------------- /work/work_md5_salt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/15 0015. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 根据用户输入的登录名和口令模拟用户注册,计算更安全的MD5 8 | import hashlib 9 | import random 10 | 11 | 12 | def get_md5(s): 13 | return hashlib.md5(s.encode('utf-8')).hexdigest() 14 | 15 | 16 | class User(object): 17 | def __init__(self, username, password): 18 | self.username = username 19 | self.password = get_md5(password + create_salt(username)) 20 | 21 | 22 | def create_salt(username): 23 | salt = '' 24 | chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' 25 | len_chars = len(chars) - 1 26 | for i in range(5): 27 | # 每次从chars中随机取一位 28 | salt += chars[random.randint(0, len_chars)] 29 | if username not in db: 30 | salt_db[username] = salt 31 | return salt 32 | 33 | 34 | 35 | 36 | db = {} 37 | salt_db = {} 38 | 39 | 40 | def regist(username, password): 41 | if username in db: 42 | print("username existed!") 43 | else: 44 | db[username] = User(username, password) 45 | 46 | 47 | def login(username, password): 48 | user = db[username] 49 | return get_md5(password + salt_db[username]) == user.password 50 | 51 | 52 | if __name__ == '__main__': 53 | # register 54 | regist('michael', '123456') 55 | regist('bob', 'abc999') 56 | regist('alice', 'alice2008') 57 | # login: 58 | assert login('michael', '123456') 59 | assert login('bob', 'abc999') 60 | assert login('alice', 'alice2008') 61 | assert not login('michael', '1234567') 62 | assert not login('bob', '123456') 63 | assert not login('alice', 'Alice2008') 64 | print('ok') 65 | -------------------------------------------------------------------------------- /work/work_regex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/12 0012. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 1. 请尝试写一个验证Email地址的正则表达式 8 | # 2. 可以提取出带名字的Email地址: 9 | import re 10 | 11 | regex_email = r"^([0-9a-zA-Z\u003C][0-9a-zA-Z\_\.\u003E\s]+?)\@([0-9a-zA-Z]+?)\.([a-z]{2,3})$" 12 | regex_email_2 = r"^\u003C([0-9a-zA-Z\s]+?)\u003E[\s]+([0-9a-zA-Z][0-9a-zA-Z\_\.]+?)$" 13 | 14 | 15 | def is_valid_email(content): 16 | return re.match(regex_email, content) 17 | 18 | 19 | def name_of_email(content): 20 | if is_valid_email(content): 21 | temp = is_valid_email(content).group(1) 22 | if re.match(regex_email_2, temp): 23 | return re.match(regex_email_2, temp).group(1) 24 | else: 25 | return temp 26 | 27 | 28 | # 测试: 29 | assert is_valid_email('someone@gmail.com') 30 | assert is_valid_email('bill.gates@microsoft.com') 31 | assert not is_valid_email('bob#example.com') 32 | assert not is_valid_email('mr-bob@example.com') 33 | print('ok') 34 | 35 | print("-" * 20) 36 | assert name_of_email(' tom@voyager.org') == 'Tom Paris' 37 | assert name_of_email('tom@voyager.org') == 'tom' 38 | print('ok') 39 | -------------------------------------------------------------------------------- /work/work_urllib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created by TaoYuan on 2017/12/18 0018. 4 | # @Link : http://blog.csdn.net/lftaoyuan 5 | # Github : https://github.com/seeways 6 | # @Remark : Python学习群:315857408 7 | # 利用urllib读取JSON,然后将JSON解析为Python对象 8 | from urllib import request 9 | import json 10 | 11 | 12 | def fetch_data(url): 13 | with request.urlopen(url) as f: 14 | try: 15 | return json.loads(f.read().decode("utf-8")) 16 | except ValueError: 17 | print("ValueError:", url) 18 | 19 | 20 | # 测试 21 | URL = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json' 22 | data = fetch_data(URL) 23 | print(data) 24 | assert data['query']['results']['channel']['location']['city'] == 'Beijing' 25 | print('ok') 26 | -------------------------------------------------------------------------------- /work/yanghui_triangles.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Date : 2017/11/21 0021 4 | # @Author : TaoYuan (1876665310@qq.com) 5 | # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 6 | # @Version : V1.0.0 7 | # @des : 杨辉三角 8 | 9 | # def triangles(): # 列表生成式 10 | # L = [1] 11 | # while True: 12 | # yield L 13 | # L.append(0) 14 | # L = [L[i - 1] + L[i] for i in range(len(L))] 15 | 16 | 17 | def triangles(): # for 循环 18 | ret = [1] 19 | while True: 20 | yield ret 21 | for i in range(1, len(ret)): 22 | ret[i] = pre[i] + pre[i - 1] 23 | ret.append(1) 24 | pre = ret[:] 25 | 26 | 27 | # def triangles(num=10): # 不用生成器 28 | # LL = [[1]] 29 | # for i in range(1, num): 30 | # LL.append( 31 | # [(0 if j == 0 else LL[i - 1][j - 1]) + (0 if j == len(LL[i - 1]) else LL[i - 1][j]) for j in range(i + 1)]) 32 | # return LL 33 | 34 | 35 | if __name__ == '__main__': 36 | n = 0 37 | results = [] 38 | for t in triangles(): 39 | print(t) 40 | results.append(t) 41 | n = n + 1 42 | if n == 10: 43 | break 44 | if results == [ 45 | [1], 46 | [1, 1], 47 | [1, 2, 1], 48 | [1, 3, 3, 1], 49 | [1, 4, 6, 4, 1], 50 | [1, 5, 10, 10, 5, 1], 51 | [1, 6, 15, 20, 15, 6, 1], 52 | [1, 7, 21, 35, 35, 21, 7, 1], 53 | [1, 8, 28, 56, 70, 56, 28, 8, 1], 54 | [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] 55 | ]: 56 | print('测试通过!') 57 | else: 58 | print('测试失败!') 59 | --------------------------------------------------------------------------------