Python tempfile.template() Examples

The following are 30 code examples of tempfile.template(). 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. You may also want to check out all available functions/classes of the module tempfile , or try the search function .
Example #1
Source File: test_tempfile.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempdir" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1,
            "TemporaryDirectory" : 1,
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.assertTrue(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example #2
Source File: api.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def mkdtemp(self, prefix=tempfile.template):
    """Makes a new temporary directory, returns Path to it.

    Args:
      * prefix (str) - a tempfile template for the directory name (defaults
        to "tmp").

    Returns a Path to the new directory.
    """
    if not self._test_data.enabled:  # pragma: no cover
      # New path as str.
      new_path = tempfile.mkdtemp(prefix=prefix, dir=str(self['cleanup']))
      # Ensure it's under self._cleanup_dir, convert to Path.
      new_path = self._split_path(new_path)
      assert new_path[:len(self._cleanup_dir)] == self._cleanup_dir, (
          'new_path: %r -- cleanup_dir: %r' % (new_path, self._cleanup_dir))
      temp_dir = self['cleanup'].join(*new_path[len(self._cleanup_dir):])
    else:
      self._test_counter += 1
      assert isinstance(prefix, basestring)
      temp_dir = self['cleanup'].join('%s_tmp_%d' %
                                      (prefix, self._test_counter))
    self.mock_add_paths(temp_dir)
    return temp_dir 
Example #3
Source File: scons-time.py    From pivy with ISC License 6 votes vote down vote up
def make_temp_file(**kw):
    try:
        result = tempfile.mktemp(**kw)
        try:
            result = os.path.realpath(result)
        except AttributeError:
            # Python 2.1 has no os.path.realpath() method.
            pass
    except TypeError:
        try:
            save_template = tempfile.template
            prefix = kw['prefix']
            del kw['prefix']
            tempfile.template = prefix
            result = tempfile.mktemp(**kw)
        finally:
            tempfile.template = save_template
    return result 
Example #4
Source File: test_tempfile.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempdir" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.assertTrue(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example #5
Source File: __init__.py    From oss-ftp with MIT License 6 votes vote down vote up
def retry_before_failing(ntimes=None):
    """Decorator which runs a test function and retries N times before
    actually failing.
    """
    def decorator(fun):
        @functools.wraps(fun)
        def wrapper(*args, **kwargs):
            for x in range(ntimes or NO_RETRIES):
                try:
                    return fun(*args, **kwargs)
                except AssertionError as _:
                    err = _
            raise err
        return wrapper
    return decorator


# commented out as per bug http://bugs.python.org/issue10354
# tempfile.template = 'tmp-pyftpdlib' 
Example #6
Source File: test_tempfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempdir" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.assertTrue(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example #7
Source File: __init__.py    From oss-ftp with MIT License 6 votes vote down vote up
def retry_before_failing(ntimes=None):
    """Decorator which runs a test function and retries N times before
    actually failing.
    """
    def decorator(fun):
        @functools.wraps(fun)
        def wrapper(*args, **kwargs):
            for x in range(ntimes or NO_RETRIES):
                try:
                    return fun(*args, **kwargs)
                except AssertionError as _:
                    err = _
            raise err
        return wrapper
    return decorator


# commented out as per bug http://bugs.python.org/issue10354
# tempfile.template = 'tmp-pyftpdlib' 
Example #8
Source File: test_tempfile.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempdir" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.assertTrue(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example #9
Source File: test_tempfile.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default_mkstemp_inner(self):
        return tempfile._mkstemp_inner(tempfile.gettempdir(),
                                       tempfile.template,
                                       '',
                                       tempfile._bin_openflags) 
Example #10
Source File: test_tempfile.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def make_temp(self):
        return tempfile._mkstemp_inner(tempfile.gettempdir(),
                                       tempfile.template,
                                       '',
                                       tempfile._bin_openflags) 
Example #11
Source File: TestCmd.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tempdir(self, path=None):
        """Creates a temporary directory.
        A unique directory name is generated if no path name is specified.
        The directory is created, and will be removed when the TestCmd
        object is destroyed.
        """
        if path is None:
            try:
                path = tempfile.mktemp(prefix=tempfile.template)
            except TypeError:
                path = tempfile.mktemp()
        os.mkdir(path)

        # Symlinks in the path will report things
        # differently from os.getcwd(), so chdir there
        # and back to fetch the canonical path.
        cwd = os.getcwd()
        try:
            os.chdir(path)
            path = os.getcwd()
        finally:
            os.chdir(cwd)

        # Uppercase the drive letter since the case of drive
        # letters is pretty much random on win32:
        drive,rest = os.path.splitdrive(path)
        if drive:
            path = drive.upper() + rest

        #
        self._dirlist.append(path)
        global _Cleanup
        try:
            _Cleanup.index(self)
        except ValueError:
            _Cleanup.append(self)

        return path 
Example #12
Source File: tempdir.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, suffix="", prefix=template, dir=None):
            self.name = mkdtemp(suffix, prefix, dir)
            self._closed = False 
Example #13
Source File: __init__.py    From PySnooper with MIT License 5 votes vote down vote up
def create_temp_folder(prefix=tempfile.template, suffix='',
                       parent_folder=None, chmod=None):
    '''
    Context manager that creates a temporary folder and deletes it after usage.

    After the suite finishes, the temporary folder and all its files and
    subfolders will be deleted.

    Example:

        with create_temp_folder() as temp_folder:

            # We have a temporary folder!
            assert temp_folder.is_dir()

            # We can create files in it:
            (temp_folder / 'my_file').open('w')

        # The suite is finished, now it's all cleaned:
        assert not temp_folder.exists()

    Use the `prefix` and `suffix` string arguments to dictate a prefix and/or a
    suffix to the temporary folder's name in the filesystem.

    If you'd like to set the permissions of the temporary folder, pass them to
    the optional `chmod` argument, like this:

        create_temp_folder(chmod=0o550)

    '''
    temp_folder = pathlib.Path(tempfile.mkdtemp(prefix=prefix, suffix=suffix,
                                                dir=parent_folder))
    try:
        if chmod is not None:
            temp_folder.chmod(chmod)
        yield temp_folder
    finally:
        shutil.rmtree(str(temp_folder)) 
Example #14
Source File: TestCmd.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tempdir(self, path=None):
        """Creates a temporary directory.
        A unique directory name is generated if no path name is specified.
        The directory is created, and will be removed when the TestCmd
        object is destroyed.
        """
        if path is None:
            try:
                path = tempfile.mktemp(prefix=tempfile.template)
            except TypeError:
                path = tempfile.mktemp()
        os.mkdir(path)

        # Symlinks in the path will report things
        # differently from os.getcwd(), so chdir there
        # and back to fetch the canonical path.
        cwd = os.getcwd()
        try:
            os.chdir(path)
            path = os.getcwd()
        finally:
            os.chdir(cwd)

        # Uppercase the drive letter since the case of drive
        # letters is pretty much random on win32:
        drive,rest = os.path.splitdrive(path)
        if drive:
            path = drive.upper() + rest

        #
        self._dirlist.append(path)
        global _Cleanup
        try:
            _Cleanup.index(self)
        except ValueError:
            _Cleanup.append(self)

        return path 
Example #15
Source File: TestCmd.py    From kawalpemilu2014 with GNU Affero General Public License v3.0 5 votes vote down vote up
def tempdir(self, path=None):
        """Creates a temporary directory.
        A unique directory name is generated if no path name is specified.
        The directory is created, and will be removed when the TestCmd
        object is destroyed.
        """
        if path is None:
            try:
                path = tempfile.mktemp(prefix=tempfile.template)
            except TypeError:
                path = tempfile.mktemp()
        os.mkdir(path)

        # Symlinks in the path will report things
        # differently from os.getcwd(), so chdir there
        # and back to fetch the canonical path.
        cwd = os.getcwd()
        try:
            os.chdir(path)
            path = os.getcwd()
        finally:
            os.chdir(cwd)

        # Uppercase the drive letter since the case of drive
        # letters is pretty much random on win32:
        drive,rest = os.path.splitdrive(path)
        if drive:
            path = string.upper(drive) + rest

        #
        self._dirlist.append(path)
        global _Cleanup
        try:
            _Cleanup.index(self)
        except ValueError:
            _Cleanup.append(self)

        return path 
Example #16
Source File: util.py    From conary with Apache License 2.0 5 votes vote down vote up
def mkstemp(suffix="", prefix=tempfile.template, dir=None, text=False):
    """
    a wrapper for tempfile.mkstemp that uses a common prefix which
    is set through settempdir()
    """
    if dir is None:
        global _tempdir
        dir = _tempdir
    return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir, text=text) 
Example #17
Source File: TestCmd.py    From android-xmrig-miner with GNU General Public License v3.0 5 votes vote down vote up
def tempdir(self, path=None):
        """Creates a temporary directory.
        A unique directory name is generated if no path name is specified.
        The directory is created, and will be removed when the TestCmd
        object is destroyed.
        """
        if path is None:
            try:
                path = tempfile.mktemp(prefix=tempfile.template)
            except TypeError:
                path = tempfile.mktemp()
        os.mkdir(path)

        # Symlinks in the path will report things
        # differently from os.getcwd(), so chdir there
        # and back to fetch the canonical path.
        cwd = os.getcwd()
        try:
            os.chdir(path)
            path = os.getcwd()
        finally:
            os.chdir(cwd)

        # Uppercase the drive letter since the case of drive
        # letters is pretty much random on win32:
        drive,rest = os.path.splitdrive(path)
        if drive:
            path = string.upper(drive) + rest

        #
        self._dirlist.append(path)
        global _Cleanup
        try:
            _Cleanup.index(self)
        except ValueError:
            _Cleanup.append(self)

        return path 
Example #18
Source File: __init__.py    From pyftpdlib with MIT License 5 votes vote down vote up
def get_server_handler():
    """Return the first FTPHandler instance running in the IOLoop."""
    ioloop = IOLoop.instance()
    for fd in ioloop.socket_map:
        instance = ioloop.socket_map[fd]
        if isinstance(instance, FTPHandler):
            return instance
    raise RuntimeError("can't find any FTPHandler instance")


# commented out as per bug http://bugs.python.org/issue10354
# tempfile.template = 'tmp-pyftpdlib' 
Example #19
Source File: tempdir.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, suffix="", prefix=template, dir=None):
            self.name = mkdtemp(suffix, prefix, dir)
            self._closed = False 
Example #20
Source File: tmpdirs.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, suffix="", prefix=template, dir=None):
        self.name = mkdtemp(suffix, prefix, dir)
        self._closed = False 
Example #21
Source File: tempdir.py    From pySINDy with MIT License 5 votes vote down vote up
def __init__(self, suffix="", prefix=template, dir=None):
            self.name = mkdtemp(suffix, prefix, dir)
            self._closed = False 
Example #22
Source File: brain_tumor_3d.py    From 3d-nii-visualizer with MIT License 5 votes vote down vote up
def redirect_vtk_messages():
    """ Redirect VTK related error messages to a file."""
    import tempfile
    tempfile.template = 'vtk-err'
    f = tempfile.mktemp('.log')
    log = vtk.vtkFileOutputWindow()
    log.SetFlush(1)
    log.SetFileName(f)
    log.SetInstance(log) 
Example #23
Source File: TestCmd.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tempdir(self, path=None):
        """Creates a temporary directory.
        A unique directory name is generated if no path name is specified.
        The directory is created, and will be removed when the TestCmd
        object is destroyed.
        """
        if path is None:
            try:
                path = tempfile.mktemp(prefix=tempfile.template)
            except TypeError:
                path = tempfile.mktemp()
        os.mkdir(path)

        # Symlinks in the path will report things
        # differently from os.getcwd(), so chdir there
        # and back to fetch the canonical path.
        cwd = os.getcwd()
        try:
            os.chdir(path)
            path = os.getcwd()
        finally:
            os.chdir(cwd)

        # Uppercase the drive letter since the case of drive
        # letters is pretty much random on win32:
        drive, rest = os.path.splitdrive(path)
        if drive:
            path = drive.upper() + rest

        #
        self._dirlist.append(path)

        global _Cleanup
        if self not in _Cleanup:
            _Cleanup.append(self)

        return path 
Example #24
Source File: __init__.py    From oss-ftp with MIT License 5 votes vote down vote up
def remove_test_files():
    """Remove files and directores created during tests."""
    for name in os.listdir(u('.')):
        if name.startswith(tempfile.template):
            if os.path.isdir(name):
                shutil.rmtree(name)
            else:
                os.remove(name) 
Example #25
Source File: __init__.py    From oss-ftp with MIT License 5 votes vote down vote up
def remove_test_files():
    """Remove files and directores created during tests."""
    for name in os.listdir(u('.')):
        if name.startswith(tempfile.template):
            if os.path.isdir(name):
                shutil.rmtree(name)
            else:
                os.remove(name) 
Example #26
Source File: tempdir.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self, suffix="", prefix=template, dir=None):
            self.name = mkdtemp(suffix, prefix, dir)
            self._closed = False 
Example #27
Source File: tempdir.py    From testpath with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, suffix="", prefix=template, dir=None):
            self.name = mkdtemp(suffix, prefix, dir)
            self._closed = False 
Example #28
Source File: test_tempfile.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def make_temp(self):
        return tempfile._mkstemp_inner(tempfile.gettempdir(),
                                       tempfile.template,
                                       '',
                                       tempfile._bin_openflags) 
Example #29
Source File: scons-time.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def make_temp_file(**kw):
    try:
        result = tempfile.mktemp(**kw)
        result = os.path.realpath(result)
    except TypeError:
        try:
            save_template = tempfile.template
            prefix = kw['prefix']
            del kw['prefix']
            tempfile.template = prefix
            result = tempfile.mktemp(**kw)
        finally:
            tempfile.template = save_template
    return result 
Example #30
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def get_fileobject(self, suffix="", prefix=tempfile.template, dir=None,
                       **kwargs):
        '''Return the temporary file to use.'''
        if dir is None:
            dir = os.path.normpath(os.path.dirname(self._path))
        descriptor, name = tempfile.mkstemp(suffix=suffix, prefix=prefix,
                                            dir=dir)
        # io.open() will take either the descriptor or the name, but we need
        # the name later for commit()/replace_atomic() and couldn't find a way
        # to get the filename from the descriptor.
        os.close(descriptor)
        kwargs['mode'] = self._mode
        kwargs['file'] = name
        return io.open(**kwargs)