
Python基础
Tsai时越
记录计算机技术学习与分享
展开
-
python3 合并m3u8文件为mp4
1.https://blog.csdn.net/qq_44575789/article/details/111998980原创 2022-06-22 06:30:24 · 535 阅读 · 0 评论 -
Python基础 利用装饰器测试程序运行时间
import timedef func_cost(func): def wrapper(*args, **kwargs): t1 = time.time() res = func(*args, **kwargs) t2 = time.time() print(func.__name__ + "执行耗时" + str(t2 - t1)) return res return wrapper@func_c原创 2022-03-04 16:42:13 · 788 阅读 · 0 评论 -
Python 中eval的强大与危害
eval是Python的一个内置函数,这个函数的作用是,返回传入字符串的表达式的结果。想象一下变量赋值时,将等号右边的表达式写成字符串的格式,将这个字符串作为eval的参数,eval的返回值就是这个表达式的结果。python中eval函数的用法十分的灵活,但也十分危险,安全性是其最大的缺点。本文从灵活性和危险性两方面介绍eval。1、强大之处举几个例子感受一下,字符串与list、tuple、dict的转化。a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"b = e转载 2021-12-24 11:31:06 · 1227 阅读 · 0 评论 -
python3 解压7z文件
最近需要用Python解压7z压缩包,发现了一个特别好用的库:py7zr,支持压缩、解压、加密、解密等等。作者对issue的反馈非常的及时和专业,甚至因为一个罕见bug还特意去linux官方的mailing-list探讨。版本要求:>=python3.5安装pip install py7zr解压7zimport py7zrwith py7zr.SevenZipFile('sample.7z', mode='r') as z: z.extractall() ```创建7转载 2021-11-28 22:26:09 · 5635 阅读 · 0 评论 -
Python 获取类名
class num: def __init__(self, num): self.num = numx = num(1)print (x.__class__)print (x.__class__.__name__)输出<class '__main__.num'>num转载 2021-10-30 11:18:35 · 4833 阅读 · 0 评论 -
Flask 项目部署
安装gunicorn服务器pip3 install gunicorn移动到flask项目app.py所在目录cd flask-project-master/3.启动gunicorn -preload -w 3 -b 0.0.0.0:8000 app:app &参考:1.Flask项目搭建及部署(完整版!全网最全)原创 2021-10-08 00:49:11 · 360 阅读 · 0 评论 -
SQLAlchemy ORM 批量插入数据几种方法
由于工作需要,需要SQLAlchemy ORM 批量插入数据,了解到以下几种批量插入方法第一种方法:s = Session()objects = [ User(name="u1"), User(name="u2"), User(name="u3")]s.bulk_save_objects(objects) 本段代码来自 http://www.chenxm.cc/post/531.html第二种方法:objects = [User(name="u1"), User(n转载 2021-10-05 06:15:30 · 3740 阅读 · 0 评论 -
SQLAlchemy 查询的时候排除掉数据库字段为 null的方法
方法1:session.query(user).filter_by(user.brand_id.isnot(None))方法2:from sqlalchemy import not_session.query(user).filter_by(not_(employ.user==None))sqlalchemy 查询数据库字段为 null的数据方法1:session.query(user).filter_by(user.brand_id.is(None))...转载 2021-10-05 06:13:43 · 1688 阅读 · 0 评论 -
python3 queue 生产者消费者模型
import threadingimport timeimport queuedef producer(): count = 1 while 1: q.put('No.%i' % count) print('Producer put No.%i' % count) time.sleep(1) count += 1def customer(name): while 1: print('%s转载 2021-09-12 16:12:58 · 237 阅读 · 0 评论 -
Python3 多线程端口扫描
import socketimport threadingimport timedef scan_port(multi_port): ClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字 ClientSocket.settimeout(2) url = "blog.csdn.net/?spm=1001.2101.3001.4477" url = url.replace("h原创 2021-09-08 15:10:38 · 801 阅读 · 0 评论 -
RPC hprose Java调用Python代码
模块pip install hprosepython server.py#!/usr/bin/env python# encoding: utf-8import hprosedef hello(name): return 'Hello %s!' % namedef main(): server = hprose.HttpServer(port=8181) server.addFunction(hello) server.start()if __原创 2021-09-06 11:57:34 · 336 阅读 · 0 评论 -
Python PIL和二进制图片互转
from PIL import Imagefrom io import BytesIOdef PIL2bytes(im): '''PIL转二进制 :param im: PIL图像,PIL.Image :return: bytes图像 ''' bytesIO = BytesIO() try: im.save(bytesIO, format='JPEG') except: im.save(bytesIO, form转载 2021-08-20 16:49:30 · 1473 阅读 · 0 评论 -
Python PIL为png图片填充上背景颜色的方法
im = Image.open('input.png')x,y = im.size try: # 填充白色背景 p = Image.new('RGBA', im.size, (255,255,255)) p.paste(im, (0, 0, x, y), im) p.save('out.png')except Exception as exc: print(exc)原创 2021-08-20 16:10:05 · 2407 阅读 · 1 评论 -
Python PIL模块Image对象、字节流对象转二进制字节流
#!usr/bin/env python# encoding:utf-8from __future__ import division '''__Author__:沂水寒城功能: Python PIL模块Image对象、字节流对象转二进制字节流''' import ioimport osimport requestsfrom PIL import Imageimport matplotlib.pyplot as plt def image2Binary():转载 2021-08-20 16:04:02 · 1165 阅读 · 0 评论 -
Python 改变和获取当前工作目录
import osos.chdir(“目标目录”) #修改当前工作目录os.getcwd() #获取当前工作目录转载 2021-08-06 11:53:05 · 344 阅读 · 0 评论 -
Python3 fitz pdf转图片base64
环境:PyMuPDF-1.18.13pip3 install fitzpip3 install PyMuPDFpip3 install pikepdf#!/user/bin/env python3# -*- coding: utf-8 -*-import base64import fitz # 若缺少fitz则可以通过pip install fitz来下载该库def pdf_convert_base64(pdf_name): pdf = fitz.Document(pdf_原创 2021-05-12 00:17:01 · 4126 阅读 · 0 评论 -
Python 上传文件到阿里云OSS
# -*- coding: utf-8 -*-import oss2import osAccessKeyId=''AccessKeySecret=''# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。auth = oss2.Auth(AccessKeyId, AccessKeySecret)# yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为原创 2021-05-18 11:36:41 · 2516 阅读 · 2 评论 -
Python3 json转换\uXXXX 编码问题
Python3中的json.dumps()出现\uXXXX:json.dumps()将中文转换为unicode编码Python 3已经将unicode作为默认编码Python 3中的json在做dumps()操作时,会将中文转换成unicode编码,并以16进制方式存储,再做loads()逆向操作时,会将unicode编码转换回中文,因此json.dumps操作后,得到的字符串是\uXXXX。解决:json.dumps()有一个ensure_ascii参数,当它为True的时候,所有非ASCII码转载 2021-04-28 11:37:20 · 1636 阅读 · 0 评论 -
python3 读取Excel xlrd.biffh.XLRDError: Excel xlsx file; not supported
原因是最近xlrd更新到了2.0.1版本,只支持.xls文件。所以pandas.read_excel(‘xxx.xlsx’)会报错。可以安装旧版xlrd,在cmd中运行:pip uninstall xlrdpip install xlrd==1.2.0转载 2021-04-28 11:31:07 · 502 阅读 · 0 评论 -
Python3 运行Java jar包
#!/user/bin/env python3# -*- coding: utf-8 -*-import os, signal,sysdef run_jar(jar_name): cmd_run = "nohup java -jar {}".format(jar_name)+" &" print(cmd_run) os.system(cmd_run) out = os.popen(cmd_run).read() if out!="":原创 2021-04-20 17:33:57 · 755 阅读 · 0 评论 -
Python3 json和字典相互转换
import json data = { 'name': 'pengjunlee', 'age': 32, 'vip': True, 'address': {'province': 'GuangDong', 'city': 'ShenZhen'}}# 将 Python 字典类型转换为 JSON 对象json_str = json.dumps(data)print(json_str) # 结果 {"name": "pengjunlee", "age": 32, "v转载 2021-04-20 15:30:26 · 841 阅读 · 0 评论 -
Python安装pip程序
1.下载安装脚本curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py2.运行安装脚本sudo python3 get-pip.py3.下载个requests库测试pip install requests原创 2021-04-15 18:17:19 · 211 阅读 · 0 评论 -
Python base64转图片
import base64# s='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHIAAABYCAYAAAAp6qMtAAAgAElEQVR4Xu1dB3hUVdo+5947JTPJpBdCKklIgCT0jlKluwoCsq5dFizr2lbFCoptdVkLu6uoK4ouKCIoIiIoICIiVST0hJJG2iSZ1Jm595zzP98594YBIY0Q9H+c5+EJhJk7d+47X3u/9/suRu34YIxh/e0wxpheyFvDsTD原创 2021-04-04 18:48:10 · 5865 阅读 · 0 评论 -
Python 定时器
每10秒打印一次from threading import Timerdef print_data(): print("1") t = Timer(10,print_data) t.start() if __name__ == '__main__': print_data()原创 2021-03-30 11:39:35 · 211 阅读 · 0 评论 -
Python sqlite3.OperationalError: near “%“: syntax error
sqlite的占位符请使用 ?原创 2021-03-13 21:33:55 · 1220 阅读 · 0 评论 -
Python3 一维数组转二维数组
#!/user/bin/env python3# -*- coding: utf-8 -*-arr = [1,2,3,4]arr2=[]for index in range(0, len(arr), 2): arr2.append(arr[index:index + 2])print(arr2)参考1.https://blog.csdn.net/chengyq116/article/details/89918640原创 2021-03-09 04:56:42 · 4423 阅读 · 0 评论 -
Python3 公历转农历
#!/user/bin/env python3# -*- coding: utf-8 -*-import sxtwllunar = sxtwl.Lunar() #实例化日历库print(lunar)ymc = [u"十一", u"十二", u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u"十" ]rmc = [u"初一", u"初二", u"初三", u"初四", u"初五", u"初六", u"初七", u"初八", u"初原创 2021-03-09 03:50:34 · 644 阅读 · 1 评论 -
Python 开启http get服务
from http.server import HTTPServer, BaseHTTPRequestHandlerimport jsonimport io, shutil, urllibhost = ('localhost', 8888)class Resquest(BaseHTTPRequestHandler): def do_GET(self): if '?' in self.path: # 如果带有参数 self.queryString =原创 2021-02-17 18:28:06 · 559 阅读 · 1 评论 -
Python 简化代码
self.flag=False判断是否为Falseif not self.flag:判断是否为Trueif self.flag:原创 2021-02-06 10:04:31 · 218 阅读 · 1 评论 -
Python list列表转str字符串
t_list=['595', '395', '547', '709', '673', '595'] # 注意里面也是str类型t_str=','.join(t_list)print(t_str) # 595,395,547,709,673,595原创 2021-01-31 16:19:36 · 591 阅读 · 0 评论 -
Python 中的 __new__(cls)方法
class Demo(object): def __init__(self): print('__init__() called...') def __new__(cls, *args, **kwargs): cls.print(cls) return object.__new__(cls, *args, **kwargs) def print(cls): print("2123")if __name__ ==原创 2021-01-25 10:46:58 · 647 阅读 · 0 评论 -
Python Excel表格创建
import xlsxwriterwb = xlsxwriter.Workbook("./test3.xlsx")ws = wb.add_worksheet("案例")# 数据data = [ ('地区', '1月销售量', '2月销售量'), ('广州', 52641, 45641,), ('上海', 65444, 54584,), ('北京', 57485, 65484,), ('深圳', 42314, 85214,)]# 字段格式header转载 2021-01-20 16:51:33 · 157 阅读 · 0 评论 -
Python基础 list列表根据值排序
student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10),]print(sorted(student_tuples, key=lambda student: student[2],reverse=True))原创 2021-01-20 15:57:35 · 607 阅读 · 0 评论 -
Python3 判断元组是否相同
import operatortuple1, tuple2 = (123, 'xyz'), (456, 'abc')print(operator.eq(tuple1, tuple2))print(operator.eq(tuple2, tuple1))tuple3 = tuple2 + (786,)print(operator.eq(tuple2, tuple3))tuple4 = (123, 'xyz')print(operator.eq(tuple1, tuple4))'''F原创 2021-01-20 10:53:23 · 6548 阅读 · 0 评论 -
Python 字符串转dict字典
s='''{'filename': '15.48.47P582751W49V4I8A1S0M0N00518c10R1E0Otunde.jpg','base_list': {'xrayno': 1, 'wheeltype': '00518c10', 'wheelbatchno': 582751, 'mouldno': '', 'wheelprocessdatetime': '2021-01-13 10:23:42'}}'''dict=eval(s)print(dict['filename'])原创 2021-01-13 11:10:25 · 746 阅读 · 0 评论 -
Python 安装whl包方式
cd 到whl包路径pip install 包名.whl原创 2020-12-28 17:59:27 · 424 阅读 · 0 评论 -
Python基础 lambda表达式
# -*- coding: utf-8 -*- fun1 = lambda x,y : x + y print('fun1(2,3)=' , fun1(2,3)) # fun1(2,3)= 5fun2 = lambda x: x*2print('fun2(4)=' , fun2(4) ) # fun2(4)= 8lambda 表达式是为了减少单行函数定义而存在的,lanbda的使用大量简化了代码,使代码简练,清晰...原创 2020-12-27 16:11:00 · 422 阅读 · 0 评论 -
Python 值传递和引用传递
值传递:传递的是不可变的数据类型,比如:number,string,tupledef fun1(a): a = 10 temp = 20fun1(temp) print(temp)#a的值发生改变,对temp的值没有影响引用传递:传递的是可变的数据类型,比如:list,dict,setdef fun2(c): c[1] = 100 d = [10,20,30,40]fun2(d)print(d)#d发生改变说明:变量中存储的地址Python之函数的基础知识转载 2020-12-25 18:48:17 · 569 阅读 · 0 评论 -
Python3 自动杀掉程序
1.根据程序名def kill_target(target): cmd_run = "ps aux | grep {}".format(target) out = os.popen(cmd_run).read() for line in out.splitlines(): print(line) if '/Users/Macbook/PycharmProjects/shiyue_100/image/server.py' in line:原创 2020-11-29 04:37:45 · 1205 阅读 · 0 评论 -
Python3 获取内外网IP
import requests,refrom bs4 import BeautifulSoup# 构造请求头headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'}# 发送get请求r=requests.get("https://www.baidu.com/s原创 2020-11-21 17:07:54 · 514 阅读 · 0 评论