Source code for Muscat.Helpers.IO.TemporaryDirectory
# -*- coding: utf-8 -*-## This file is subject to the terms and conditions defined in# file 'LICENSE.txt', which is part of this source code package.#fromtypingimportTupleimportosimportsysimportsubprocessimportshutilimporttempfileimportstatfromMuscat.Helpers.IO.WhichimportWhich
[docs]classTemporaryDirectory():"""Class to generate and to destroy a temporary directory """path:str=Noneprefix:str="Muscat_Test_Directory_"createdOnRam=False
[docs]@classmethoddefGetTempPath(cls,onRam:bool=False)->str:"""Get and Create (if needed) a temporary directory Parameters ---------- onRam : bool, optional, default False if true an on ram directory is created (only on linux ), by default None, on disk Returns ------- str Path to the temporary directory """ifcls.pathisnotNoneand(onRam==cls.createdOnRam):returncls.pathifonRamandnotsys.platform.startswith('linux'):# pragma: no coverraiseException("ERROR! can create a temporary directory on ran only on linux.")ifonRam:# only posix coveragecls.path:str=tempfile.mkdtemp(prefix=cls.prefix,suffix="_safe_to_delete",dir="/dev/shm/")+os.sepcls.createdOnRam=Trueelse:cls.path=tempfile.mkdtemp(prefix=cls.prefix,suffix="_safe_to_delete")+os.sepcls.createdOnRam=Falsecls.__saveTempPath()returncls.path
# we cant test this function, because the temp path will be delete
[docs]@classmethoddefDeleteTempPath(cls)->None:"""Delete the temporary directory and all its content """ifcls.pathisnotNone:shutil.rmtree(cls.path)cls.path=None
[docs]@classmethoddefOpenTempFolder(cls)->None:# pragma: no cover"""Open a file explorer on the temporary directory """ifos.sys.platform=="win32":subprocess.Popen(f'explorer "{cls.GetTempPath()}"')elifos.platform=="darwin":subprocess.Popen(f'open "{cls.GetTempPath()}"')elifWhich("nautilus"):subprocess.Popen(['nautilus',cls.GetTempPath()])
[docs]@classmethoddefSetTempPath(cls,path:str)->None:"""Set the temporary path from the given path Parameters ---------- path : str temporary path to be created, no error is raised if the directory already exists. """cls.path=os.path.abspath(path+os.sep)+os.sepifnotos.path.exists(cls.path):os.makedirs(cls.path)cls.__saveTempPath()
@classmethoddef__saveTempPath(cls)->None:"""Save the temporary path to the user home directory This very useful in combination of a alias: alias cdtmp='source ~/.MuscatToolsTempPath' """home:str=os.path.expanduser("~")withopen(home+os.sep+".MuscatToolsTempPath","w")asf:f.write("cd "+cls.path.replace("\\","/")+"\n")os.chmod(home+os.sep+".MuscatToolsTempPath",stat.S_IWUSR|stat.S_IRUSR|stat.S_IXUSR)
[docs]@classmethoddefGetFullFilenameOnTempDirectory(cls,filename:str)->str:"""Return an absolute path to filename in the temporary directory if pathname is an absolute path then this function return path Parameters ---------- filename : str relative (to the temp path) or absolute filename Returns ------- str full filename (with path) in the temporary directory """ifos.path.isabs(filename):returnfilenameelse:returnos.path.abspath(cls.GetTempPath()+filename)
[docs]defCheckIntegrity(GUI:bool=False):fromMuscat.Helpers.IO.TemporaryDirectoryimportTemporaryDirectorysaveTempPath=TemporaryDirectory.pathtry:TemporaryDirectory.path=Nonepath=TemporaryDirectory.GetTempPath()path2=TemporaryDirectory.GetTempPath()assert(path==path2)TemporaryDirectory.DeleteTempPath()TemporaryDirectory.SetTempPath(path)TemporaryDirectory.DeleteTempPath()path=TemporaryDirectory.GetTempPath(onRam=False)path2=TemporaryDirectory.GetTempPath(onRam=False)assert(path==path2)path=TemporaryDirectory.GetFullFilenameOnTempDirectory("toto")path=TemporaryDirectory.GetFullFilenameOnTempDirectory("/toto")TemporaryDirectory.path=Noneifsys.platform.startswith("linux"):# only posix coverageprint(f"{TemporaryDirectory.GetTempPath(onRam=True)=}")ifGUI:# pragma no coverageTemporaryDirectory.OpenTempFolder()except:# pragma no coverageTemporaryDirectory.path=saveTempPathraisereturn"ok"