
Python
vtenten
代码搬运工
-
原创 Python 字典列表,根据字段字段进行排序。
对字典列表进行排序from operator import itemgetter# 有如下一个列表,我们需要给其中的字典进行排序,比如根据uid排序rows = [ {'name': 'Brian', 'id': 1003}, {'name': 'David', 'id': 1002}, {'name': 'John', 'id': 1001}, {'name': 'Big', 'id': 1004}, {'name': 'Ag', 'id': 1004}]2020-11-02 23:41:26747
0
-
原创 Python 列表循环删除
案例列表循环删除中,第一次很容易采坑如下面案例,我们想把列表中 2全部删除alist = [1,2,3,1,2,2,3,4]for i in alist: if i == 2: alist.remove(i)print(alist)我们希望得到 [1, 3, 1, 3, 4]结果 [1, 3, 1, 2, 3, 4,有一个2漏掉了分析for循环一个list的时候,每次循环Index索引+1。如果这个时候动态的改变列表比如第一次循环 索引Index =2020-10-15 21:14:4881
0
-
原创 Python bisect对有序序列进行插入值的操作
import bisect# 使用bisect前,需要先排序data = [4, 2, 9, 7]data.sort() # 排序print("sort", data)bisect.insort(data, 3)print("bisect.insort", data) # 插入并排序index = bisect.bisect(data, 0)print("bisect.bisect", data) # 不会插入,返回如果插入的话,插入的位置print("bisect.bisect -2020-09-21 00:38:1591
0
-
原创 Python 动态导入
Python 动态导入首先是项目目录结构其中 lib_a.py 和lib_b.py 代码如图# lib_a.pydef do_something(): print("this is lib_a.py") # lib_b.pydef do_something(): print("this is lib_a.py")main代码如下#!/usr/bin/env python# coding:utf8import importlibmodule_name =2020-09-17 22:19:4275
0
-
原创 Python Sched定时任务
sched 定时任务模块# coding:utf8import timeimport sched# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。# 一般情况就使用time.time, time.sleep即可s = sched.scheduler(time.time, time.sleep)# 获取时间戳的函数 2020-09-16 19:03:01def get_time(): return time.strftime("%Y-%m-%d .2020-09-16 22:52:57135
0
-
原创 Python PDB 调试
PDBpython内置的调试工具,Python Debugger支持断点、单步调试、支持流程控制、支持堆栈检查。支持源码嵌入,也可以事后进行调试。源码嵌入调试就是在源代码中嵌入pdb语法,进行打断点。这种import pdbdef add(a,b): c = a + b pdb.set_trace() return cprint(add(3,4))事后进行调试# a.pydef add(a,b): c = a + b return c2020-09-15 22:52:3560
0
-
原创 Python Schedule定时任务
# 参考 https://zhuanlan.zhihu.com/p/23086148import scheduleimport time def job(name): print("her name is : ", name) name = "xxxxxxxxxx"schedule.every(2).seconds.do(job, name)schedule.every(10).minutes.do(job, name)schedule.every().hour.do(job,2020-09-14 22:53:36116
0
-
原创 Python 获取时间戳,与本地时间不符,更改时区
Python 获取时间戳,与本地时间不符,时区不对https://www.cnblogs.com/mashuqi/p/11576705.html更改时区就可以了ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime2020-08-04 10:09:32987
0
-
原创 Python 异步操作文件 aiofiles
# 异步文件操作# pip install aiofiles# 基本用法import asyncioimport aiofilesasync def wirte_demo(): # 异步方式执行with操作,修改为 async with async with aiofiles.open("text.txt","w",encoding="utf-8") as fp: await fp.write("hello world ") print("数据2020-07-31 16:39:031570
0
-
原创 Python 异步框架FastAPI
安装pip install fastapi# 部署使用pip install uvicornHello Worldfrom typing import Optionalfrom fastapi import FastAPIapp = FastAPI()@app.get("/")async def read_root(): return {"Hello": "World"}# http://localhost:8000/items/it5?q=123456# it2020-07-27 17:37:46241
0
-
原创 Python 类似defer 延迟调用的功能
go语言中有 deferimport "fmt"func myfunc() { fmt.Println("B")}func main() { defer myfunc() fmt.Println("A")}python 使用 上下文管理器实现同样的效果import contextlibdef func_D(k,v): print(f"{k}:{v}")def func_C(): print('C')def func_B(): prin2020-07-27 14:23:05123
0
-
原创 Python 使用asyncio tcp
使用 asyncio streams 编写 TCP 客户端和服务端的程序回显: tcp客户端发送什么,服务端就会返回什么本程序发送一次,客户端就会自动断开。客户端import asyncioasync def tcp_echo_client(message): reader, writer = await asyncio.open_connection( '127.0.0.1', 8888) print(f'Send: {message!r}') w2020-07-24 10:17:37789
0
-
原创 Python asyncio官方文档 之 高级API - 协程与任务篇
asyncio — 异步 I/O¶版本:Python 3.7 +asyncio 是用来编写 并发 代码的库,使用 async/await 关键字。Hello World !import asyncioasync def main(): print('Hello ...') await asyncio.sleep(1) print('... World!')# Python 3.7+asyncio.run(main())官方目录下面是官方文档提供的asyncio2020-07-23 23:53:24180
0
-
原创 Python 通过定时器,停止无线循环的线程
有一个无线循环的线程再执行任务,当外部长时间没有import threadingimport time# 定时器触发时,执行的函数,停止进程def stop_stream(live): live.stop() print("stop the rtsp stream")# 重置定时器,如果我们输入了内容,则定时器会执行cancel() 和 start(),定时器时间被重置了def listen_timer(): global timer while Tr.2020-07-16 15:15:28740
0
-
原创 Python partial 返回带参的函数对象
编写python程序时候,可能会出现这么一种情况。一个函数的参数,需要传入一个函数名def func_a(): passdef main(func): func()那么,如果func_a是带参数的怎么办呢? 我们不能把func_a(参数)传入到main中只能传入函数名func_apartial,为我么解决了这个问题使用partial,包装一个函数,返回一个函数名。...2019-01-22 10:13:11346
0
-
原创 使用pillow, 生成一张图片验证码
pillow 博客文档模块pillow使用安装pip install pillow生成图片验证码图片验证码需要使用到字体,一般字体库为ttf后缀结尾的文件,可以网上自省下载,这里我提供一个分享的下载地址。链接:https://pan.baidu.com/s/1MnzaZuxmEPGkNpMBMKjuEA提取码:nunuimport randomfrom PIL import Image,ImageDraw,ImageFont,ImageFilterdef check_code2020-06-29 18:00:55165
0
-
原创 aiohttp websocket 简单使用
import aiohttpfrom aiohttp import webpersonal_pool = {}room_pool = {}# 发送消息async def broadcast_msg(user_name,msg,room=""): # 如果不是聊天室,则单独返回 if not room: ws = personal_pool[user_name] await ws.send_str("服务器接收到了您的信息") # 如果是2020-06-24 09:29:46657
0
-
原创 Python opencv 视频图片添加时间戳
图片添加文字import cv2img = cv2.imread('pyyy.png')img2 = img.copy() # 备份操作font = cv2.FONT_HERSHEY_SIMPLEX # 定义字体imgzi = cv2.putText(img, '000', (50, 50), font, 1.2, (255, 255, 255), 2) # 图像,文字内容, 坐标 ,字体,大小,颜色,字体厚度cv2.imshow('origin',2020-06-09 09:03:14797
0
-
原创 Python aiohttp中间件示例
aiohttp# 获取表单data = await self.request.post()# 获取url /{user_id}/ 中的参数user_id = self.request.match_info.get('user_id')# 获取Jsondata = await self.request.json()# 获取get参数name = self.request.query.get("name")aiohttp 中间件from aiohttp import webfro2020-05-27 19:09:27140
0
-
原创 python web JWT认证
前后端分离之JWT认证方式原文 https://www.jianshu.com/p/180a870a308aJWT 即 json web token为什么会使用JWT?1*.http协议是无状态的*2.如果使用传统方式,将session保存到数据库中,增大了服务器数据库存储压力3.多数据库session需要时时同步4.大型网站是多站点,多个域名组成的,使用set cookie ...2018-11-27 20:55:411177
0
-
原创 Python 使用argparse进行命令行解析
prog.pyimport argparse# 1. 创建一个解析器parser = argparse.ArgumentParser(description='Process some integers.')# 2.添加参数# metavar是help显示的参数名(默认大写),我们重新赋值空不显示# 2.1 integers 是位置参数parser.add_argument('integers',type=int,metavar="N",help='an integer for the a2020-05-19 09:32:22111
0
-
原创 Python 枚举类
def judge(color): if color == 1 or color == 2: print("司机违规") else: print("司机正常行驶")使用枚举类from enum import Enumclass TrafficLight(Enum): RED = 1 YELLOW = 2 GREEN ...2020-03-26 09:36:4152
0
-
原创 Python回收进程,防止僵尸进程的出现
通过信号回收子进程,防止出现僵尸进程# sig.pyfrom multiprocessing import Processimport loggingimport osimport signalimport timelogging.basicConfig( level=logging.DEBUG, format='%(asctime)-15s - %(levelna...2019-12-04 15:17:391611
0
-
原创 python reload() 重载,重新加载模块
# python2 内置函数reload(module)# python3 from imp import reloadreload(module)说明:module 必须是已经成功导入的模块模块被加载到内存以后,更改文件内容,已经运行的程序不会生效的,可通过reload重新加载。导入是一个开销很大的操作。...2019-10-28 09:27:263454
1
-
原创 python多进程获取返回值
import multiprocessingfrom multiprocessing import Managerdef worker(procnum, return_dict): '''worker function''' print(str(procnum) + ' represent!') return_dict[procnum] = procnumif _...2018-12-29 11:32:5112175
1
-
原创 使用time模块 获取时间戳,毫秒
使用time模块 获取时间戳注意本机 本地时间。import timedef get_timestamp(): """ 获取时间戳和带有格式的时间 """ ct = time.time() local_time = time.localtime(ct) data_head = str(time.strftime("%Y%m2018-08-15 09:44:2314129
0
-
原创 python函数注释,参数后面加冒号:,函数后面的箭头→是什么?
函数注释示例:def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here": print("函数注释", f.__annotations__) print("参数值打印", ham, eggs) print(type(ham),type(eggs))f("www")返回信息:函数注释 {'ham':...2018-10-12 09:57:3234748
0