Python get temp dir

59 Python code examples are found related to " get temp dir". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: googletest.py    From lambda-packs with MIT License 6 votes vote down vote up
def GetTempDir():
  """Return a temporary directory for tests to use."""
  global _googletest_temp_dir
  if not _googletest_temp_dir:
    first_frame = tf_inspect.stack()[-1][0]
    temp_dir = os.path.join(tempfile.gettempdir(),
                            os.path.basename(tf_inspect.getfile(first_frame)))
    temp_dir = tempfile.mkdtemp(prefix=temp_dir.rstrip('.py'))

    def delete_temp_dir(dirname=temp_dir):
      try:
        file_io.delete_recursively(dirname)
      except errors.OpError as e:
        logging.error('Error removing %s: %s', dirname, e)

    atexit.register(delete_temp_dir)
    _googletest_temp_dir = temp_dir

  return _googletest_temp_dir 
Example 2
Source File: provider.py    From streamalert with Apache License 2.0 6 votes vote down vote up
def get_local_credentials_temp_dir():
        """Returns a temporary directory on the filesystem to store encrypted credentials.

        Will automatically create the new directory if it does not exist.

        Returns:
            str: local path for streamalert_secrets tmp directory
        """
        temp_dir = os.path.join(tempfile.gettempdir(), "streamalert_secrets")

        # Check if this item exists as a file, and remove it if it does
        if os.path.isfile(temp_dir):
            os.remove(temp_dir)

        # Create the folder on disk to store the credentials temporarily
        if not os.path.exists(temp_dir):
            os.makedirs(temp_dir)

        return temp_dir 
Example 3
Source File: export.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def get_temp_export_dir(timestamped_export_dir):
  """Builds a directory name based on the argument but starting with 'temp-'.

  This relies on the fact that TensorFlow Serving ignores subdirectories of
  the base directory that can't be parsed as integers.

  Args:
    timestamped_export_dir: the name of the eventual export directory, e.g.
      /foo/bar/<timestamp>

  Returns:
    A sister directory prefixed with 'temp-', e.g. /foo/bar/temp-<timestamp>.
  """
  (dirname, basename) = os.path.split(timestamped_export_dir)
  temp_export_dir = os.path.join(
      compat.as_bytes(dirname),
      compat.as_bytes('temp-{}'.format(basename)))
  return temp_export_dir 
Example 4
Source File: platform.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def get_temp_dir():
    shellvars = ['${TMP}', '${TEMP}']
    dir_root = get_dir_root(shellvars, default_to_home=False)

    #this method is preferred to the envvars
    if os.name == 'nt':
        try_dir_root = win32api.GetTempPath()
        if try_dir_root is not None:
            dir_root = try_dir_root

    if dir_root is None:
        try_dir_root = None
        if os.name == 'nt':
            # this should basically never happen. GetTempPath always returns something
            try_dir_root = r'C:\WINDOWS\Temp'
        elif os.name == 'posix':
            try_dir_root = '/tmp'
        if (try_dir_root is not None and
            os.path.isdir(try_dir_root) and
            os.access(try_dir_root, os.R_OK|os.W_OK)):
            dir_root = try_dir_root
    return dir_root 
Example 5
Source File: resource_processor.py    From cotk with Apache License 2.0 5 votes vote down vote up
def get_temp_dir(self, filepath: str):
		"""Get a temp directory, in which some temporary files may be saved.
		The temp directory is a subdirectory of `self.cache_dr` and is named after the hash value of argument `filepath`,
		so that the same `filepath` has the same corresponding temp directory.
		"""
		abs_path = os.path.abspath(filepath)
		hash_value = hashlib.sha256(abs_path.encode('utf-8')).hexdigest()
		return os.path.join(self.cache_dir, hash_value + '_temp')

#TODO: merge the following Processor because of duplicate codes 
Example 6
Source File: connection.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_good_temp_dir(self):
        """
        Return the 'good temporary directory' as discovered by
        :func:`ansible_mitogen.target.init_child` immediately after
        ContextService constructed the target context.
        """
        self._connect()
        return self.init_child_result['good_temp_dir'] 
Example 7
Source File: runner.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_temp_dir(self):
        path = self.args.get('_ansible_tmpdir')
        if path is not None:
            return path

        if self._temp_dir is None:
            self._temp_dir = tempfile.mkdtemp(
                prefix='ansible_mitogen_runner_',
                dir=self.good_temp_dir,
            )

        return self._temp_dir 
Example 8
Source File: file.py    From EasyClangComplete with MIT License 5 votes vote down vote up
def get_temp_dir(*subfolders):
        """Create a temporary folder if needed and return it."""
        tempdir = path.join(tempfile.gettempdir(), PKG_NAME, *subfolders)
        try:
            makedirs(tempdir)
        except OSError:
            log.debug("Folder %s exists.", tempdir)
        return tempdir 
Example 9
Source File: misc_util.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def get_build_temp_dir(self):
        """
        Return a path to a temporary directory where temporary files should be
        placed.
        """
        cmd = get_cmd('build')
        cmd.ensure_finalized()
        return cmd.build_temp 
Example 10
Source File: util.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_temp_dir():
    # get name of a temp directory which will be automatically cleaned up
    if current_process()._tempdir is None:
        import shutil, tempfile
        tempdir = tempfile.mkdtemp(prefix='pymp-')
        info('created temp directory %s', tempdir)
        Finalize(None, shutil.rmtree, args=[tempdir], exitpriority=-100)
        current_process()._tempdir = tempdir
    return current_process()._tempdir

#
# Support for reinitialization of objects when bootstrapping a child process
# 
Example 11
Source File: utils.py    From ray with Apache License 2.0 5 votes vote down vote up
def get_user_temp_dir():
    if sys.platform.startswith("darwin") or sys.platform.startswith("linux"):
        # Ideally we wouldn't need this fallback, but keep it for now for
        # for compatibility
        tempdir = os.path.join(os.sep, "tmp")
    else:
        tempdir = tempfile.gettempdir()
    return tempdir 
Example 12
Source File: files.py    From cgat-core with MIT License 5 votes vote down vote up
def get_temp_dir(dir=None, shared=False, clear=False):
    '''get a temporary directory.

    The directory is created and the caller needs to delete the temporary
    directory once it is not used any more.

    If dir does not exist, it will be created.

    Arguments
    ---------
    dir : string
        Directory of the temporary directory and if not given is set to the
        default temporary location in the global configuration dictionary.
    shared : bool
        If set, the tempory directory will be in a shared temporary
        location.

    Returns
    -------
    filename : string
        Absolute pathname of temporary file.

    '''
    if dir is None:
        if shared:
            dir = get_params()['shared_tmpdir']
        else:
            dir = get_params()['tmpdir']

    if not os.path.exists(dir):
        os.makedirs(dir)

    tmpdir = tempfile.mkdtemp(dir=dir, prefix="ctmp")
    if clear:
        os.rmdir(tmpdir)
    return tmpdir 
Example 13
Source File: tools.py    From ibmsecurity with Apache License 2.0 5 votes vote down vote up
def get_random_temp_dir():
    """
    Create a temporary directory
    """
    import os
    import tempfile
    tmpdir = tempfile.gettempdir()
    random_str = random_password(10, allow_special=False)
    tmpdir += '/%s' % random_str
    os.mkdir(tmpdir)
    return tmpdir 
Example 14
Source File: abstractFileStore.py    From toil with Apache License 2.0 5 votes vote down vote up
def getLocalTempDir(self):
        """
        Get a new local temporary directory in which to write files that persist for the duration of
        the job.

        :return: The absolute path to a new local temporary directory. This directory will exist
                 for the duration of the job only, and is guaranteed to be deleted once the job
                 terminates, removing all files it contains recursively.
        :rtype: str
        """
        return os.path.abspath(tempfile.mkdtemp(prefix="t", dir=self.localTempDir)) 
Example 15
Source File: common.py    From synapse with Apache License 2.0 5 votes vote down vote up
def getTempDir():
    tempdir = tempfile.mkdtemp()

    try:
        yield tempdir

    finally:
        shutil.rmtree(tempdir, ignore_errors=True) 
Example 16
Source File: tf_utils.py    From hub with Apache License 2.0 5 votes vote down vote up
def get_temp_export_dir(timestamped_export_dir):
  """Builds a directory name based on the argument but starting with 'temp-'.

  This relies on the fact that TensorFlow Serving ignores subdirectories of
  the base directory that can't be parsed as integers.

  Args:
    timestamped_export_dir: the name of the eventual export directory, e.g.
      /foo/bar/<timestamp>

  Returns:
    A sister directory prefixed with 'temp-', e.g. /foo/bar/temp-<timestamp>.
  """
  dirname, basename = os.path.split(tf.compat.as_bytes(timestamped_export_dir))
  return os.path.join(dirname, b"temp-" + basename)


# Note: This is written from scratch to mimic the pattern in:
# `tf_v1.estimator.LatestExporter._garbage_collect_exports()`. 
Example 17
Source File: config.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def get_temp_dir_path(config: Optional[ConfigParser] = None) -> str:
    temp_dir_path = config.get('data_storage', 'temp_dir_path', fallback='/tmp') if config else '/tmp'
    if not Path(temp_dir_path).is_dir():
        try:
            Path(temp_dir_path).mkdir()
        except OSError:
            logging.error('TempDir path does not exist and could not be created. Defaulting to /tmp', exc_info=True)
            return '/tmp'
    return temp_dir_path 
Example 18
Source File: QuincyUtils.py    From quincy with GNU General Public License v3.0 5 votes vote down vote up
def getTempDir():
    if platform.system() == 'Linux':
        tempdir = tempfile.mkdtemp(dir='/dev/shm')
    else:
        tempdir = tempfile.mkdtemp()
    logging.debug("Created temp dir: %r" % tempdir)
    return tempdir 
Example 19
Source File: Files.py    From CGATPipelines with MIT License 5 votes vote down vote up
def getTempDir(dir=None, shared=False):
    '''get a temporary directory.

    The directory is created and the caller needs to delete the temporary
    directory once it is not used any more.

    Arguments
    ---------
    dir : string
        Directory of the temporary directory and if not given is set to the
        default temporary location in the global configuration dictionary.
    shared : bool
        If set, the tempory directory will be in a shared temporary
        location.

    Returns
    -------
    filename : string
        Absolute pathname of temporary file.

    '''
    if dir is None:
        if shared:
            dir = PARAMS['shared_tmpdir']
        else:
            dir = PARAMS['tmpdir']

    return tempfile.mkdtemp(dir=dir, prefix="ctmp") 
Example 20
Source File: googletest.py    From keras-lambda with MIT License 5 votes vote down vote up
def GetTempDir():
  first_frame = inspect.stack()[-1][0]
  temp_dir = os.path.join(
      tempfile.gettempdir(), os.path.basename(inspect.getfile(first_frame)))
  temp_dir = temp_dir.rstrip('.py')
  if not os.path.isdir(temp_dir):
    os.mkdir(temp_dir, 0o755)
  return temp_dir 
Example 21
Source File: file_util.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def get_temp_dir(self):
        temp = self.get_environ_variable("TMP")
        if not temp: temp = self.get_environ_variable("TEMP")
        if (not temp or ' ' in temp) and os.name == 'nt': 
            temp = r"C:\temp"
        if (not temp or ' ' in temp) and os.name == 'posix': 
            temp = "/tmp"

        return temp 
Example 22
Source File: pipelinewise.py    From pipelinewise with Apache License 2.0 5 votes vote down vote up
def get_temp_dir(self):
        """
        Returns the tap specific temp directory
        """
        return os.path.join(self.config_dir, 'tmp') 
Example 23
Source File: utils.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def get_temp_dir():
  """Return the temp dir."""
  temp_dirname = 'temp-' + str(os.getpid())
  temp_directory = os.path.join(
      environment.get_value('FUZZ_INPUTS_DISK'), temp_dirname)
  shell.create_directory(temp_directory)
  return temp_directory 
Example 24
Source File: util.py    From romcollectionbrowser with GNU General Public License v2.0 5 votes vote down vote up
def getTempDir():
    tempDir = os.path.join(getAddonDataPath(), 'tmp')

    try:
        #check if folder exists
        if not os.path.isdir(tempDir):
            os.mkdir(tempDir)
        return tempDir
    except Exception as exc:
        Logutil.log('Error creating temp dir: ' + str(exc), LOG_LEVEL_ERROR)
        return None 
Example 25
Source File: temp.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def get_temp_dir(category: str) -> str:
    """Accessor for the temp directory."""
    if category not in TEMP_DIRS:
        TEMP_DIRS[category] = tempfile.TemporaryDirectory(category)
    return TEMP_DIRS[category].name 
Example 26
Source File: temp_file.py    From dagster with Apache License 2.0 5 votes vote down vote up
def get_temp_dir(in_directory=None):
    temp_dir = None
    try:
        temp_dir = tempfile.mkdtemp(dir=in_directory)
        yield temp_dir
    finally:
        if temp_dir:
            shutil.rmtree(temp_dir) 
Example 27
Source File: importtasks.py    From contentdb with GNU General Public License v3.0 5 votes vote down vote up
def getTempDir():
	return os.path.join(tempfile.gettempdir(), randomString(10))


# Clones a repo from an unvalidated URL.
# Returns a tuple of path and repo on sucess.
# Throws `TaskError` on failure.
# Caller is responsible for deleting returned directory. 
Example 28
Source File: video.py    From phd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_temp_dir_size(self):
        """
        Returns the size of the temp dir.
        """
        return sizeof_fmt(get_dir_size(self.temp_dir)) 
Example 29
Source File: utils.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def get_temp_dir(keep=False):
    """Creates a temporary file, and returns its name.

    :param keep: If False (default), the directory will be recursively
                 deleted when Scapy exits.
    :return: A full path to a temporary directory.
    """

    dname = tempfile.mkdtemp(prefix="scapy")

    if not keep:
        conf.temp_files.append(dname)

    return dname 
Example 30
Source File: util.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def get_temp_dir():
    # get name of a temp directory which will be automatically cleaned up
    tempdir = process.current_process()._config.get('tempdir')
    if tempdir is None:
        import shutil, tempfile
        tempdir = tempfile.mkdtemp(prefix='pymp-')
        info('created temp directory %s', tempdir)
        Finalize(None, shutil.rmtree, args=[tempdir], exitpriority=-100)
        process.current_process()._config['tempdir'] = tempdir
    return tempdir

#
# Support for reinitialization of objects when bootstrapping a child process
# 
Example 31
Source File: lib.py    From keras-pandas with MIT License 5 votes vote down vote up
def get_temp_dir():
    temp_dir = tempfile.mkdtemp(prefix='python_starter')
    logging.info('Created temp_dir: {}'.format(temp_dir))
    print('Created temp_dir: {}'.format(temp_dir))
    return temp_dir