目录
一、同步与异步下载
1.同步下载
2.异步下载
二、文件合并
三、批量替换文件指定内容
四、连接数据库执行
五、exe带参运行
打包exe
python实用代码,在日常中可能偶尔用到需要用python来完成我们一些繁琐的操作,包括一些小工具,本文章记录日常用到的python代码,并且封装好即拿即用,快速开发。
一、同步与异步下载
1.同步下载
如使用pip安装requests
如:pip install requests
使用前需要安装以下模块
import requests
import re
import os
from tqdm import tqdm
tqdm是一个进度条模块,加上会有下载进度条,for i in tqdm(arr):
# 下载链接,路径,文件名
def download(self,url, path,name):
response = requests.get(url, headers=self.header)#请求
if not os.path.exists(path):#判断路径是否存在
# 不存在创建
os.makedirs(path)
with open(path+"/"+name, "wb") as f:#wb二进制
f.write(response.content)
2.异步下载
import requests
import re
import os
from tqdm import tqdm
#异步
import asyncio
import aiohttp
import aiofiles
#异步读取下载函数,下载链接,路径,文件名
async def ReadTsAsync(url,path,name):
tasks=[]#任务列表
timeout = aiohttp.ClientTimeout(total=500) # 将超时时间设置为500秒
connector = aiohttp.TCPConnector(limit=50) # 将并发数量降低
async with aiohttp.ClientSession(connector=connector,timeout=timeout) as session:#提前准备好创建,到下载ts文件函数时不用每次都创建,在调用时传过去
async with aiofiles.open(f"{path}/temp/{name}",mode="r",encoding='utf-8') as f:
async for ts in f:
if ts.startswith("#"):#号开头的行
continue
#拼接链接
tsUrl=TsUrlIf(url,ts)#拼接函数
task=asyncio.create_task(TsDownloadAsync(path,tsUrl,ts,session))#创建任务,传
tasks.append(task)
# print("任务添加成功")
await asyncio.wait(tasks)#等待任务结束
把每一个TsDownloadAsync(path,tsUrl,ts,session)添加到列表异步下载
#文件异步下载
async def TsDownloadAsync(path, url, ts, session):
# loop = asyncio.get_event_loop()
try:
async with session.get(url, verify_ssl=False) as request:
async with aiofiles.open(f"{path}/temp/{ts}".replace("\n", ""), mode="wb") as f:
await f.write(await request.content.read())
print("\r", f"{ts}下载中", end="", flush=True)
except Exception as e:
print(f"下载网络不稳定:{e}")
return False
使用:开启线程任务
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(ReadTsAsync(url,path,name))
二、文件合并
使用二进制的方式追加写入
# 合并方法,路径,文件名,临时文件夹
def Mp4(path,name):
f = open(f"{path}/temp/{name}", 'r')
arr = re.findall(',\n(.*?)\n#', f.read()) # f.read()读取文件,截取需要的内容
for ts in arr:
try:
with open(f"{path}/temp/{ts}", "rb") as f:
data_name = f.read()
with open(f"{path}/video.mp4", "ab") as f: # ab追加
f.write(data_name) # 写入
except Exception as e:
print(f"资源部分丢失,但仍然可看:{e}")
上面是一个合成mp4的列子,改成其他名即可合成
三、批量替换文件指定内容
import os
def updateFile(file, old_str, new_str):
"""
替换文件中的字符串
:param file:文件名
:param old_str:就字符串
:param new_str:新字符串
:return:
"""
file_data = ""
with open(file, "r", encoding="UTF-18") as f:
for line in f:
if old_str in line:
line = line.replace(old_str, new_str)
file_data += line
with open(file, "w", encoding="UTF-18") as f:
f.write(file_data)
path=input("请输入目录路径:")
str_old=input("请输入需要替换掉的字符:")
str_new = input("请输入替换后的新字符:")
for root, dirs, files in os.walk(path, topdown=False):
for i in files:
print(i)
updateFile(path+"\\"+i, str_old, str_new)
print("=========替换完成=========")
需要根据你当前文件字符编码来修改UTF-18
四、连接数据库执行
import pymysql
con=pymysql.connect(
host="",
port="",
user="",
password="",
db=""
)
db=con.cursor()
sql=""
db.execute(sql)
con.commit()#提交事务
db.close()
五、exe带参运行
类似于py.exe -f ‘测试’
import sys
if len(sys.argv)==1:
print("error")
sys.exit(1)
elif sys.argv[1]=="-f":
print("yes")
打包exe
先安装pyinstaller模块,cmd执行
pip install pyinstaller
打包命令
pyinstaller -F -i favicon.ico cs.py
pyinstaller -F -w -i favicon.ico cs.py -p 其他模块.py
-F:将整个程序打包为一个exe文件,需要注意的是,与-D模式生成的exe程序相比,在启动速度上会慢一点,原因是它需要先解压exe文件并生成一个唯一的临时环境来运行程序,关闭环境时也会自动删除这个临时环境,-D模式的程序本身就是解压好的,运行完也不需要执行删除操作,当程序比较大时,这个差别就很明显了。
-D:创建一个目录,包含exe文件,但会依赖很多文件(默认选项)
与F/–onefile参数作用相反,将程序打包为一个文件夹,文件夹中包含启动程序的exe文件和其他依赖的资源文件和DLL文件等。
-w:表示程序运行后隐藏命令行窗口,当你不需要使用命令行窗口作为程序的I/O时,比如GUI程序,可以使用这个参数选项。
-c:默认选项,与 -w 相反,提供一个命令行窗口进行 I/O。
-i:指定exe程序图标。
-p: 添加搜索路径,让其找到对应的库。