otwrapy.TempWorkDir

class TempWorkDir(dir=None, base_temp_work_dir=None, prefix='run-', cleanup=False, transfer=None, chdir=False)

Implement a context manager that creates a temporary working directory.

Create a temporary working directory in dir preceded by prefix and clean up at the exit if necessary.

Parameters:
dirstr, optional

Root path where the temporary working directory will be created. If None, it will default to the platform dependent temporary working directory Default = None

prefixstr, optional

String that preceeds the directory name. Default = ‘run-’

cleanupbool, optional

If True erase the directory and its children at the exit. Default = False

transferlist, optional

List of files or folders to transfer to the temporary working directory

chdirbool, optional

Whether to change directory to the temporary working directory. Default is False, should not be necessary and intended for backward compatibility only.

Examples

In the following example, everything that is executed inside the with environment will happen at a temporary working directory created at /tmp with /run- as a prefix. The created directory will be erased upon the exit of the with environment, even if an Exception is raised.

>>> import otwrapy as otw
>>> import subprocess
>>> with otw.TempWorkDir('/tmp', prefix='run-', cleanup=True) as cwd:
>>> ... print(cwd)
>>> ... # [write input files]
>>> ... subprocess.run(["myexe", "input.txt"], cwd=cwd)
>>> ... # [read output files]
__init__(dir=None, base_temp_work_dir=None, prefix='run-', cleanup=False, transfer=None, chdir=False)

Methods

__init__([dir, base_temp_work_dir, prefix, ...])