Temppathlib provides wrappers around tempfile so that you can directly use them together with pathlib module.
We found it cumbersome to convert tempfile objects manually to pathlib.Path whenever we needed a temporary
file.
Additionally, we also provide:
- a context manager
removing_treethat checks if a path exists and recursively deletes it by wrappingshutil.rmtree. - a context manager
TmpDirIfNecessarythat creates a temporary directory if no directory is given and otherwise uses a supplied directory. This is useful when you want to keep some of the temporary files for examination after the program finished. We usually specify an optional--operation_dircommand-line argument to our programs and pass its value to theTmpDirIfNecessary.
If you need a more complex library to transition from string paths to pathlib.Path, have a look at
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- Create a virtual environment:
python3 -m venv venv3- Activate it:
source venv3/bin/activate- Install temppathlib with pip:
pip3 install temppathlib- Check out the repository.
- In the repository root, create the virtual environment:
python3 -m venv venv3- Activate the virtual environment:
source venv3/bin/activate- Install the development dependencies:
pip3 install -e .[dev]- We use tox for testing and packaging the distribution. Assuming that the virtual environment has been activated and the development dependencies have been installed, run:
tox- We also provide a set of pre-commit checks that lint and check code for formatting. Run them locally from an activated virtual environment with development dependencies:
./precommit.py- The pre-commit script can also automatically format the code:
./precommit.py --overwriteWe follow Semantic Versioning. The version X.Y.Z indicates:
- X is the major version (backward-incompatible),
- Y is the minor version (backward-compatible), and
- Z is the patch version (backward-compatible bug fix).