####################################################################### BioSimSpace: Making biomolecular simulation a breeze!## Copyright: 2017-2024## Authors: Lester Hedges <lester.hedges@gmail.com>## BioSimSpace is free software: you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation, either version 3 of the License, or# (at your option) any later version.## BioSimSpace is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with BioSimSpace. If not, see <http://www.gnu.org/licenses/>.#####################################################################"""Custom context managers."""__author__="Lester Hedges"__email__="lester.hedges@gmail.com"__all__=["WorkDir"]importosas_osimporttempfileas_tempfile
[docs]classWorkDir:"""A utility class to create a working directory."""
[docs]def__init__(self,work_dir=None):""" Constructor. Parameters ---------- work_dir : str The working directory for the context. If None, then a temporary working directory will be created. """# Validate the input.ifwork_dirandnotisinstance(work_dir,str):raiseTypeError("'work_dir' must be of type 'str'")# Temporary directory.ifwork_dirisNone:self._tmp_dir=_tempfile.TemporaryDirectory()self._work_dir=self._tmp_dir.name# User specified directory.else:self._tmp_dir=None# Use absolute path.ifnot_os.path.isabs(work_dir):work_dir=_os.path.abspath(work_dir)# Create the directory if it doesn't already exist.ifnot_os.path.isdir(work_dir):_os.makedirs(work_dir,exist_ok=True)self._work_dir=work_dir
def__str__(self):returnself._work_dirdef__repr__(self):returnself._work_dirdef__add__(self,other):ifnotisinstance(other,str):raiseTypeError(f"unsupported operand type(s) for +: 'WorkDir' and '{type(other)}'")returnstr(self._work_dir)+other
[docs]defis_temp_dir(self):"""Whether this is a temporary directory."""returnself._tmp_dirisnotNone