包装tempfile以提供pathlib.path。
temppathlib的Python项目详细描述
临时路径库
temppathlib为tempfile提供包装器,以便您可以直接将它们与pathlib模块一起使用。 我们发现在需要临时对象时手动将tempfile对象转换为pathlib.Path很麻烦 文件。
此外,我们还提供:
- 上下文管理器{TT5}$,检查路径是否存在并递归删除它 通过包装shutil.rmtree。
- 上下文管理器TmpDirIfNecessary,如果没有给定目录,则创建临时目录,否则 使用提供的目录。当您想保留一些临时文件以供检查时,这很有用 节目结束后。我们通常为程序指定一个可选的--operation_dir命令行参数 并将其值传递给TmpDirIfNecessary。
如果需要更复杂的库来从字符串路径转换到pathlib.Path,请查看 ruamel.std.pathlib。
用法
importpathlibimporttemppathlib# create a temporary directorywithtemppathlib.TemporaryDirectory()astmp_dir:tmp_pth=tmp_dir.path/"some-filename.txt"# do something else with tmp_dir ...# create a temporary filewithtemppathlib.NamedTemporaryFile()astmp:# write to ittmp.file.write('hello'.encode())tmp.file.flush()# you can use its path.target_pth=pathlib.Path('/some/permanent/directory')/tmp.path.name# create a temporary directory only if necessaryoperation_dir=pathlib.Path("/some/operation/directory)withtemppathlib.TmpDirIfNecessary(path=operation_dir)asop_dir:# do something with the operation directorypth=op_dir.path/"some-file.txt"# operation_dir is not deleted since 'path' was specified.withtemppathlib.TmpDirIfNecessary()asop_dir:# do something with the operation directorypth=op_dir.path/"some-file.txt"# op_dir is deleted since 'path' argument was not specified.# context manager to remove the path recursivelypth=pathlib.Path('/some/directory')withtemppathlib.removing_tree(pth):# do something in the directory ...pass
安装
- 创建虚拟环境:
python3 -m venv venv3
- 启动:
source venv3/bin/activate
- 使用pip: 安装temppathlib
pip3 install temppathlib
开发
- 查看存储库。
- 在存储库根目录中,创建虚拟环境:
python3 -m venv venv3
- 激活虚拟环境:
source venv3/bin/activate
- 安装开发依赖项:
pip3 install -e .[dev]
- 我们用毒物测试和包装分发。假设虚拟环境已激活并且 开发依赖项已安装,运行:
tox
- 我们还提供了一组预提交检查,lint和检查代码的格式。从激活的 具有开发依赖关系的虚拟环境:
./precommit.py
- 预提交脚本还可以自动格式化代码:
./precommit.py --overwrite