Python tips

标签: python, 技巧 ;


本文收集一些经常用到,又经常忘记的小技巧。算是我自己的 cook book。

文件操作

创建压缩文件

# 压缩单个文件
import zipfile
with zipfile.ZipFile('output_path', 'w', zipfile.ZIP_DEFLATED) as zo:
    zo.write('in_path', os.path.basename('file_path'))
# output_path 为输出文件的完整路径
# in_path 为待压缩的文件完整路径
# os.path.basename 从完整路径中获取文件名,使得被压缩文件在zip中以独立文件存在,而不是处于各级目录之下

# 压缩一整个目录
import shutil
shutil.make_archive(output_filename, 'zip', dir_name)

判断操作系统

创建单实例应用

让flask 或类似的应用自我结束

之前werkzeug开发服务器有一个自己退出的API,现在废弃了。替代的方法是直接调用操作系统的API kill 掉自己的进程。

import os, signal, sys
def shutdown_server():
    os.kill(os.getpid(), signal.SIGINT)

@app.get('/shutdown')
def shutdown():
    #print('接收到退出指令')
    if sys.platform.startswith('win32'):
        shutdown_server()
        return 'Server shutting down...'
    return 'Only the Windows version supports this operation'