Python tempfile.gettempprefix() Examples

The following are code examples for showing how to use tempfile.gettempprefix(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 8 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            try:
                fd = os.open(p, os.O_RDWR | os.O_CREAT)
            except:
                self.failOnException("os.open")
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 7 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 3
Project: JukeBox   Author: gauravsarkar97   File: _temp.py    MIT License 6 votes vote down vote up
def mkstemp(suffix=None, prefix=None, dir=None, text=False):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
        text (bool): if the file should be opened in text mode
    Returns:
        Tuple[`int`, `fsnative`]:
            A tuple containing the file descriptor and the file path
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative`
    path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkstemp(suffix, prefix, dir, text) 
Example 4
Project: JukeBox   Author: gauravsarkar97   File: _temp.py    MIT License 6 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
    Returns:
        `fsnative`: A path to a directory
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative` path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkdtemp(suffix, prefix, dir) 
Example 5
Project: senf   Author: quodlibet   File: _temp.py    MIT License 6 votes vote down vote up
def mkstemp(suffix=None, prefix=None, dir=None, text=False):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
        text (bool): if the file should be opened in text mode
    Returns:
        Tuple[`int`, `fsnative`]:
            A tuple containing the file descriptor and the file path
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative`
    path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkstemp(suffix, prefix, dir, text) 
Example 6
Project: senf   Author: quodlibet   File: _temp.py    MIT License 6 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
    Returns:
        `fsnative`: A path to a directory
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative` path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkdtemp(suffix, prefix, dir) 
Example 7
Project: deb-python-rjsmin   Author: openstack   File: shell.py    Apache License 2.0 6 votes vote down vote up
def mkstemp(suffix="", prefix=_tempfile.gettempprefix(), dir=None,
                text=False):
        """ Create secure temp file """
        # pylint: disable = W0622
        if dir is None:
            dir = _tempfile.gettempdir()
        if text:
            flags = _text_openflags
        else:
            flags = _bin_openflags
        count = 100
        while count > 0:
            j = _tempfile._counter.get_next() # pylint: disable = E1101, W0212
            fname = _os.path.join(dir, prefix + str(j) + suffix)
            try:
                fd = _os.open(fname, flags, 0600)
            except OSError, e:
                if e.errno == _errno.EEXIST:
                    count -= 1
                    continue
                raise
            _set_cloexec(fd)
            return fd, _os.path.abspath(fname) 
Example 8
Project: bugatsinho.github.io   Author: bugatsinho   File: _temp.py    GNU General Public License v3.0 6 votes vote down vote up
def mkstemp(suffix=None, prefix=None, dir=None, text=False):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
        text (bool): if the file should be opened in text mode
    Returns:
        Tuple[`int`, `fsnative`]:
            A tuple containing the file descriptor and the file path
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative`
    path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkstemp(suffix, prefix, dir, text) 
Example 9
Project: bugatsinho.github.io   Author: bugatsinho   File: _temp.py    GNU General Public License v3.0 6 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
    Returns:
        `fsnative`: A path to a directory
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative` path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkdtemp(suffix, prefix, dir) 
Example 10
Project: messenger-emulator   Author: sDextra   File: _temp.py    MIT License 6 votes vote down vote up
def mkstemp(suffix=None, prefix=None, dir=None, text=False):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
        text (bool): if the file should be opened in text mode
    Returns:
        Tuple[`int`, `fsnative`]:
            A tuple containing the file descriptor and the file path
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative`
    path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkstemp(suffix, prefix, dir, text) 
Example 11
Project: messenger-emulator   Author: sDextra   File: _temp.py    MIT License 6 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
    Returns:
        `fsnative`: A path to a directory
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative` path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkdtemp(suffix, prefix, dir) 
Example 12
Project: ironpython2   Author: IronLanguages   File: test_tempfile.py    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 13
Project: ironpython2   Author: IronLanguages   File: test_tempfile.py    Apache License 2.0 6 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            try:
                fd = os.open(p, os.O_RDWR | os.O_CREAT)
            except:
                self.failOnException("os.open")
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 14
Project: deb-python-rcssmin   Author: openstack   File: shell.py    Apache License 2.0 6 votes vote down vote up
def mkstemp(suffix="", prefix=_tempfile.gettempprefix(), dir=None,
                text=False):
        """ Create secure temp file """
        # pylint: disable = W0622
        if dir is None:
            dir = _tempfile.gettempdir()
        if text:
            flags = _text_openflags
        else:
            flags = _bin_openflags
        count = 100
        while count > 0:
            j = _tempfile._counter.get_next() # pylint: disable = E1101, W0212
            fname = _os.path.join(dir, prefix + str(j) + suffix)
            try:
                fd = _os.open(fname, flags, 0600)
            except OSError, e:
                if e.errno == _errno.EEXIST:
                    count -= 1
                    continue
                raise
            _set_cloexec(fd)
            return fd, _os.path.abspath(fname) 
Example 15
Project: oss-ftp   Author: aliyun   File: test_tempfile.py    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 16
Project: oss-ftp   Author: aliyun   File: test_tempfile.py    MIT License 6 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            try:
                fd = os.open(p, os.O_RDWR | os.O_CREAT)
            except:
                self.failOnException("os.open")
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 17
Project: py2rb   Author: naitoh   File: env_tests.py    MIT License 6 votes vote down vote up
def runTest(self):
        """The actual test goes here."""
        if os.system(
            "ruby --help > %s" %
            os.path.join(
                tempfile.gettempdir(),
                tempfile.gettempprefix()
                )
            ):
            self.stop()
            raise RuntimeError("""Can't find the "ruby" command.""")
        self.reportProgres()
        if not os.path.exists("py2rb/builtins/module.rb"):
            self.stop()
            raise RuntimeError("""Can't find the "py2rb/builtins/module.rb" command.""")
        if not os.path.exists("py2rb/builtins/require.rb"):
            self.stop()
            raise RuntimeError("""Can't find the "py2rb/builtins/require.rb" command.""")
        self.reportProgres() 
Example 18
Project: har2warc   Author: webrecorder   File: test_har2warc.py    Apache License 2.0 6 votes vote down vote up
def test_load_http2_warc_convert_protocol(self):
        filename = self.get_test_file('http2.github.io.har')

        temp_filename = os.path.join(tempfile.gettempdir(), tempfile.gettempprefix() + '-http2.warc')

        try:
            # write then read same file
            with open(temp_filename, 'w+b') as fh:
                har2warc(filename, fh)

                fh.seek(0)

                ai = ArchiveIterator(fh, verify_http=True)

                record = next(ai)
                assert record.rec_type == 'warcinfo'

                record = next(ai)
                assert record.rec_type == 'response'

                # ensure protocol vonerted to HTTP/1.1
                assert record.http_headers.protocol == 'HTTP/1.1'

        finally:
            os.remove(temp_filename) 
Example 19
Project: Hot   Author: dsolimando   File: test_tempfile.py    GNU General Public License v3.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
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.failUnless(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example 20
Project: Hot   Author: dsolimando   File: test_tempfile.py    GNU General Public License v3.0 6 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            try:
                fd = os.open(p, os.O_RDWR | os.O_CREAT)
            except:
                self.failOnException("os.open")
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 21
Project: dj-tango   Author: flccrakers   File: _temp.py    GNU General Public License v3.0 6 votes vote down vote up
def mkstemp(suffix=None, prefix=None, dir=None, text=False):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
        text (bool): if the file should be opened in text mode
    Returns:
        Tuple[`int`, `fsnative`]:
            A tuple containing the file descriptor and the file path
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative`
    path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkstemp(suffix, prefix, dir, text) 
Example 22
Project: dj-tango   Author: flccrakers   File: _temp.py    GNU General Public License v3.0 6 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
    Returns:
        `fsnative`: A path to a directory
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative` path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkdtemp(suffix, prefix, dir) 
Example 23
Project: my_hass_config   Author: ivencooli   File: _temp.py    MIT License 6 votes vote down vote up
def mkstemp(suffix=None, prefix=None, dir=None, text=False):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
        text (bool): if the file should be opened in text mode
    Returns:
        Tuple[`int`, `fsnative`]:
            A tuple containing the file descriptor and the file path
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative`
    path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkstemp(suffix, prefix, dir, text) 
Example 24
Project: my_hass_config   Author: ivencooli   File: _temp.py    MIT License 6 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """
    Args:
        suffix (`pathlike` or `None`): suffix or `None` to use the default
        prefix (`pathlike` or `None`): prefix or `None` to use the default
        dir (`pathlike` or `None`): temp dir or `None` to use the default
    Returns:
        `fsnative`: A path to a directory
    Raises:
        EnvironmentError

    Like :func:`python3:tempfile.mkstemp` but always returns a `fsnative` path.
    """

    suffix = fsnative() if suffix is None else path2fsn(suffix)
    prefix = gettempprefix() if prefix is None else path2fsn(prefix)
    dir = gettempdir() if dir is None else path2fsn(dir)

    return tempfile.mkdtemp(suffix, prefix, dir) 
Example 25
Project: rawkit   Author: photoshell   File: raw.py    MIT License 6 votes vote down vote up
def __init__(self, filename=None):
        """Initializes a new DarkFrame object."""
        super(DarkFrame, self).__init__(filename=filename)
        self.options = Options({
            'auto_brightness': False,
            'brightness': 1.0,
            'auto_stretch': True,
            'bps': 16,
            'gamma': (1, 1),
            'rotation': 0,
        })
        self._tmp = os.path.join(
            tempfile.gettempdir(),
            '{prefix}{rand}'.format(
                prefix=tempfile.gettempprefix(),
                rand=''.join(random.SystemRandom().choice(
                    string.ascii_uppercase + string.digits) for _ in range(8)
                )
            )
        )
        self._filetype = None 
Example 26
Project: csvtotable   Author: vividvilla   File: convert.py    MIT License 6 votes vote down vote up
def serve(content):
    """Write content to a temp file and serve it in browser"""
    temp_folder = tempfile.gettempdir()
    temp_file_name = tempfile.gettempprefix() + str(uuid.uuid4()) + ".html"
    # Generate a file path with a random name in temporary dir
    temp_file_path = os.path.join(temp_folder, temp_file_name)

    # save content to temp file
    save(temp_file_path, content)

    # Open templfile in a browser
    webbrowser.open("file://{}".format(temp_file_path))

    # Block the thread while content is served
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        # cleanup the temp file
        os.remove(temp_file_path) 
Example 27
Project: dcos-e2e   Author: dcos   File: doctor.py    Apache License 2.0 6 votes vote down vote up
def _check_tmp_free_space() -> CheckLevels:
    """
    Warn if there is not enough free space in the default temporary directory.
    """
    free_space = shutil.disk_usage(gettempdir()).free
    free_space_gb = free_space / 1024 / 1024 / 1024

    low_space_message = (
        'The default temporary directory ("{tmp_prefix}") has '
        '{free_space:.1f} GB of free space available. '
        'Creating a cluster typically takes approximately 2 GB of temporary '
        'storage. '
        'If you encounter problems with disk space usage, set the ``TMPDIR`` '
        'environment variable to a suitable temporary directory or use the '
        '``--workspace-dir`` option on the ``minidcos docker create`` command.'
    ).format(
        tmp_prefix=Path('/') / gettempprefix(),
        free_space=free_space_gb,
    )

    if free_space_gb < 5:
        warn(message=low_space_message)
        return CheckLevels.WARNING

    return CheckLevels.NONE 
Example 28
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assertIsInstance(p, basestring)
        self.assertTrue(len(p) > 0) 
Example 29
Project: JukeBox   Author: gauravsarkar97   File: _temp.py    MIT License 5 votes vote down vote up
def gettempprefix():
    """
    Returns:
        `fsnative`

    Like :func:`python3:tempfile.gettempprefix`, but always returns a
    `fsnative` path
    """

    return path2fsn(tempfile.gettempprefix()) 
Example 30
Project: senf   Author: quodlibet   File: _temp.py    MIT License 5 votes vote down vote up
def gettempprefix():
    """
    Returns:
        `fsnative`

    Like :func:`python3:tempfile.gettempprefix`, but always returns a
    `fsnative` path
    """

    return path2fsn(tempfile.gettempprefix()) 
Example 31
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 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,
            "gettempprefixb" : 1,
            "gettempdir" : 1,
            "gettempdirb" : 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 32
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def make_temp(self):
        return tempfile._mkstemp_inner(tempfile.gettempdir(),
                                       tempfile.gettempprefix(),
                                       '',
                                       tempfile._bin_openflags,
                                       str) 
Example 33
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assertIsInstance(p, str)
        self.assertGreater(len(p), 0)

        pb = tempfile.gettempprefixb()

        self.assertIsInstance(pb, bytes)
        self.assertGreater(len(pb), 0) 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            fd = os.open(p, os.O_RDWR | os.O_CREAT)
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 35
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: weave_test_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def empty_temp_dir():
    """Create a sub directory in the temp directory for use in tests"""
    d = catalog.default_dir()
    for i in range(10000):
        new_d = os.path.join(d,tempfile.gettempprefix()[1:-1]+repr(i))
        if not os.path.exists(new_d):
            os.mkdir(new_d)
            break
    return new_d 
Example 36
Project: bugatsinho.github.io   Author: bugatsinho   File: _temp.py    GNU General Public License v3.0 5 votes vote down vote up
def gettempprefix():
    """
    Returns:
        `fsnative`

    Like :func:`python3:tempfile.gettempprefix`, but always returns a
    `fsnative` path
    """

    return path2fsn(tempfile.gettempprefix()) 
Example 37
Project: messenger-emulator   Author: sDextra   File: _temp.py    MIT License 5 votes vote down vote up
def gettempprefix():
    """
    Returns:
        `fsnative`

    Like :func:`python3:tempfile.gettempprefix`, but always returns a
    `fsnative` path
    """

    return path2fsn(tempfile.gettempprefix()) 
Example 38
Project: ironpython2   Author: IronLanguages   File: test_tempfile.py    Apache License 2.0 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assertIsInstance(p, basestring)
        self.assertTrue(len(p) > 0) 
Example 39
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_tempfile.py    GNU General Public License v2.0 5 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,
            "gettempprefixb" : 1,
            "gettempdir" : 1,
            "gettempdirb" : 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 40
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_tempfile.py    GNU General Public License v2.0 5 votes vote down vote up
def make_temp(self):
        return tempfile._mkstemp_inner(tempfile.gettempdir(),
                                       tempfile.gettempprefix(),
                                       '',
                                       tempfile._bin_openflags,
                                       str) 
Example 41
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_tempfile.py    GNU General Public License v2.0 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assertIsInstance(p, str)
        self.assertGreater(len(p), 0)

        pb = tempfile.gettempprefixb()

        self.assertIsInstance(pb, bytes)
        self.assertGreater(len(pb), 0) 
Example 42
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_tempfile.py    GNU General Public License v2.0 5 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            fd = os.open(p, os.O_RDWR | os.O_CREAT)
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 43
Project: oss-ftp   Author: aliyun   File: test_tempfile.py    MIT License 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assertIsInstance(p, basestring)
        self.assertTrue(len(p) > 0) 
Example 44
Project: poker   Author: surgebiswas   File: weave_test_utils.py    MIT License 5 votes vote down vote up
def empty_temp_dir():
    """Create a sub directory in the temp directory for use in tests"""
    d = catalog.default_dir()
    for i in range(10000):
        new_d = os.path.join(d,tempfile.gettempprefix()[1:-1]+repr(i))
        if not os.path.exists(new_d):
            os.mkdir(new_d)
            break
    return new_d 
Example 45
Project: PyDevNS   Author: daveisadork   File: conftest.py    MIT License 5 votes vote down vote up
def resolver_dir(config):
    resolvers = []
    config.resolver_dir = os.path.join(
        tempfile.gettempdir(),
        "{0}-{1}".format(tempfile.gettempprefix(), "resolver")
    )
    resolvers.append(config.resolver_dir)
    yield config.resolver_dir
    resolvers.append(config.resolver_dir)
    for resolver in filter(None, set(resolvers)):
        if os.path.isdir(resolver):
            os.rmdir(resolver) 
Example 46
Project: har2warc   Author: webrecorder   File: test_har2warc.py    Apache License 2.0 5 votes vote down vote up
def load_har(self, filename):
        filename = self.get_test_file(filename)

        temp_filename = os.path.join(tempfile.gettempdir(), tempfile.gettempprefix() + '-' + os.path.basename(filename))

        try:
            main([filename, temp_filename])

            with patch_stdout() as buff:
                indexer(['index', temp_filename, '-f', 'warc-target-uri'])

                return buff.getvalue().decode('utf-8')
        finally:
            os.remove(temp_filename) 
Example 47
Project: Hot   Author: dsolimando   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assert_(isinstance(p, basestring))
        self.assert_(len(p) > 0) 
Example 48
Project: kingpin   Author: pinterest   File: zk_update_monitor.py    Apache License 2.0 5 votes vote down vote up
def transform_command_with_value(command, value, notification_timestamp):
    python_download_script = 'zk_download_data.py'

    if len(value) > _LONG_VALUE_THRESHOLD:
        # If the value is too long (serverset is too large), OSError may be thrown.
        # Instead of passing it in command line, write to a temp file and
        # let zk_download_data read from it.
        value = value.replace("\n", "").replace("\r", "")
        md5digest = zk_util.get_md5_digest(value)
        tmp_filename = 'zk_update_largefile_' + md5digest + '_' + str(notification_timestamp)
        tmp_dir = tempfile.gettempprefix()
        tmp_filepath = os.path.join('/', tmp_dir, tmp_filename)

        log.info("This is a long value, write it to temp file %s", tmp_filepath)
        try:
            with open(tmp_filepath, 'w') as f:
                f.write(value + '\n' + md5digest)
        except Exception as e:
            log.exception(
                "%s: Failed to generate temp file %s for storing large size values"
                % (e.message, tmp_filepath))
            return (None, None)
        finally:
            f.close()
        transformed_command = command.replace(
            python_download_script, "%s -l %s" % (
                python_download_script, tmp_filepath))
        return transformed_command, tmp_filepath
    else:
        transformed_command = command.replace(
            python_download_script, "%s -v '%s'" % (
                python_download_script, value))
        return transformed_command, None 
Example 49
Project: dj-tango   Author: flccrakers   File: _temp.py    GNU General Public License v3.0 5 votes vote down vote up
def gettempprefix():
    """
    Returns:
        `fsnative`

    Like :func:`python3:tempfile.gettempprefix`, but always returns a
    `fsnative` path
    """

    return path2fsn(tempfile.gettempprefix()) 
Example 50
Project: pyhow   Author: yoeo   File: tempfile.py    MIT License 5 votes vote down vote up
def gettempprefix():
    """Prefix of temporary directories and files."""

    return "prefix is {}".format(tempfile.gettempprefix()) 
Example 51
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_tempfile.py    GNU General Public License v3.0 5 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,
            "gettempprefixb" : 1,
            "gettempdir" : 1,
            "gettempdirb" : 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 52
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def make_temp(self):
        return tempfile._mkstemp_inner(tempfile.gettempdir(),
                                       tempfile.gettempprefix(),
                                       '',
                                       tempfile._bin_openflags,
                                       str) 
Example 53
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assertIsInstance(p, str)
        self.assertGreater(len(p), 0)

        pb = tempfile.gettempprefixb()

        self.assertIsInstance(pb, bytes)
        self.assertGreater(len(pb), 0) 
Example 54
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            fd = os.open(p, os.O_RDWR | os.O_CREAT)
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 55
Project: cells   Author: AlesTsurko   File: test_tempfile.py    MIT License 5 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,
            "gettempprefixb" : 1,
            "gettempdir" : 1,
            "gettempdirb" : 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 56
Project: cells   Author: AlesTsurko   File: test_tempfile.py    MIT License 5 votes vote down vote up
def make_temp(self):
        return tempfile._mkstemp_inner(tempfile.gettempdir(),
                                       tempfile.gettempprefix(),
                                       '',
                                       tempfile._bin_openflags,
                                       str) 
Example 57
Project: cells   Author: AlesTsurko   File: test_tempfile.py    MIT License 5 votes vote down vote up
def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assertIsInstance(p, str)
        self.assertGreater(len(p), 0)

        pb = tempfile.gettempprefixb()

        self.assertIsInstance(pb, bytes)
        self.assertGreater(len(pb), 0) 
Example 58
Project: cells   Author: AlesTsurko   File: test_tempfile.py    MIT License 5 votes vote down vote up
def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            fd = os.open(p, os.O_RDWR | os.O_CREAT)
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d) 
Example 59
Project: my_hass_config   Author: ivencooli   File: _temp.py    MIT License 5 votes vote down vote up
def gettempprefix():
    """
    Returns:
        `fsnative`

    Like :func:`python3:tempfile.gettempprefix`, but always returns a
    `fsnative` path
    """

    return path2fsn(tempfile.gettempprefix()) 
Example 60
Project: deskOrg   Author: saleguas   File: pydocview.py    MIT License 4 votes vote down vote up
def OnInit(self):
        """
        Initializes the DocApp.
        """
        self._services = []
        self._defaultIcon = None
        self._registeredCloseEvent = False
        self._useTabbedMDI = True

        if not hasattr(self, "_debug"):  # only set if not already initialized
            self._debug = False
        if not hasattr(self, "_singleInstance"):  # only set if not already initialized
            self._singleInstance = True

        # if _singleInstance is TRUE only allow one single instance of app to run.
        # When user tries to run a second instance of the app, abort startup,
        # But if user also specifies files to open in command line, send message to running app to open those files
        if self._singleInstance:
            # create shared memory temporary file
            if wx.Platform == '__WXMSW__':
                tfile = tempfile.TemporaryFile(prefix="ag", suffix="tmp")
                fno = tfile.fileno()
                self._sharedMemory = mmap.mmap(fno, 1024, "shared_memory")
            else:
                tfile = file(os.path.join(tempfile.gettempdir(), tempfile.gettempprefix() + self.GetAppName() + '-' + wx.GetUserId() + "AGSharedMemory"), 'w+b')
                tfile.write("*")
                tfile.seek(1024)
                tfile.write(" ")
                tfile.flush()
                fno = tfile.fileno()
                self._sharedMemory = mmap.mmap(fno, 1024)

            self._singleInstanceChecker = wx.SingleInstanceChecker(self.GetAppName() + '-' + wx.GetUserId(), tempfile.gettempdir())
            if self._singleInstanceChecker.IsAnotherRunning():
                # have running single instance open file arguments
                data = pickle.dumps(sys.argv[1:])
                while 1:
                    self._sharedMemory.seek(0)
                    marker = self._sharedMemory.read_byte()
                    if marker == '\0' or marker == '*':        # available buffer
                        self._sharedMemory.seek(0)
                        self._sharedMemory.write_byte('-')     # set writing marker
                        self._sharedMemory.write(data)  # write files we tried to open to shared memory
                        self._sharedMemory.seek(0)
                        self._sharedMemory.write_byte('+')     # set finished writing marker
                        self._sharedMemory.flush()
                        break
                    else:
                        time.sleep(1)  # give enough time for buffer to be available

                return False
            else:
                self._timer = wx.PyTimer(self.DoBackgroundListenAndLoad)
                self._timer.Start(250)

        return True 
Example 61
Project: Rovers   Author: RIT-Space-Exploration   File: frontend.py    MIT License 4 votes vote down vote up
def run(self):
        po_files = []
        if not self.output_file:
            if self.locale:
                po_files.append((self.locale,
                                 os.path.join(self.output_dir, self.locale,
                                              'LC_MESSAGES',
                                              self.domain + '.po')))
            else:
                for locale in os.listdir(self.output_dir):
                    po_file = os.path.join(self.output_dir, locale,
                                           'LC_MESSAGES',
                                           self.domain + '.po')
                    if os.path.exists(po_file):
                        po_files.append((locale, po_file))
        else:
            po_files.append((self.locale, self.output_file))

        if not po_files:
            raise DistutilsOptionError('no message catalogs found')

        domain = self.domain
        if not domain:
            domain = os.path.splitext(os.path.basename(self.input_file))[0]

        with open(self.input_file, 'rb') as infile:
            template = read_po(infile)

        for locale, filename in po_files:
            self.log.info('updating catalog %s based on %s', filename, self.input_file)
            with open(filename, 'rb') as infile:
                catalog = read_po(infile, locale=locale, domain=domain)

            catalog.update(
                template, self.no_fuzzy_matching,
                update_header_comment=self.update_header_comment
            )

            tmpname = os.path.join(os.path.dirname(filename),
                                   tempfile.gettempprefix() +
                                   os.path.basename(filename))
            try:
                with open(tmpname, 'wb') as tmpfile:
                    write_po(tmpfile, catalog,
                             ignore_obsolete=self.ignore_obsolete,
                             include_previous=self.previous, width=self.width)
            except:
                os.remove(tmpname)
                raise

            try:
                os.rename(tmpname, filename)
            except OSError:
                # We're probably on Windows, which doesn't support atomic
                # renames, at least not through Python
                # If the error is in fact due to a permissions problem, that
                # same error is going to be raised from one of the following
                # operations
                os.remove(filename)
                shutil.copy(tmpname, filename)
                os.remove(tmpname) 
Example 62
Project: Rovers   Author: RIT-Space-Exploration   File: frontend.py    MIT License 4 votes vote down vote up
def run(self):
        po_files = []
        if not self.output_file:
            if self.locale:
                po_files.append((self.locale,
                                 os.path.join(self.output_dir, self.locale,
                                              'LC_MESSAGES',
                                              self.domain + '.po')))
            else:
                for locale in os.listdir(self.output_dir):
                    po_file = os.path.join(self.output_dir, locale,
                                           'LC_MESSAGES',
                                           self.domain + '.po')
                    if os.path.exists(po_file):
                        po_files.append((locale, po_file))
        else:
            po_files.append((self.locale, self.output_file))

        if not po_files:
            raise DistutilsOptionError('no message catalogs found')

        domain = self.domain
        if not domain:
            domain = os.path.splitext(os.path.basename(self.input_file))[0]

        with open(self.input_file, 'rb') as infile:
            template = read_po(infile)

        for locale, filename in po_files:
            self.log.info('updating catalog %s based on %s', filename, self.input_file)
            with open(filename, 'rb') as infile:
                catalog = read_po(infile, locale=locale, domain=domain)

            catalog.update(
                template, self.no_fuzzy_matching,
                update_header_comment=self.update_header_comment
            )

            tmpname = os.path.join(os.path.dirname(filename),
                                   tempfile.gettempprefix() +
                                   os.path.basename(filename))
            try:
                with open(tmpname, 'wb') as tmpfile:
                    write_po(tmpfile, catalog,
                             ignore_obsolete=self.ignore_obsolete,
                             include_previous=self.previous, width=self.width)
            except:
                os.remove(tmpname)
                raise

            try:
                os.rename(tmpname, filename)
            except OSError:
                # We're probably on Windows, which doesn't support atomic
                # renames, at least not through Python
                # If the error is in fact due to a permissions problem, that
                # same error is going to be raised from one of the following
                # operations
                os.remove(filename)
                shutil.copy(tmpname, filename)
                os.remove(tmpname) 
Example 63
Project: pySINDy   Author: luckystarufo   File: frontend.py    MIT License 4 votes vote down vote up
def run(self):
        po_files = []
        if not self.output_file:
            if self.locale:
                po_files.append((self.locale,
                                 os.path.join(self.output_dir, self.locale,
                                              'LC_MESSAGES',
                                              self.domain + '.po')))
            else:
                for locale in os.listdir(self.output_dir):
                    po_file = os.path.join(self.output_dir, locale,
                                           'LC_MESSAGES',
                                           self.domain + '.po')
                    if os.path.exists(po_file):
                        po_files.append((locale, po_file))
        else:
            po_files.append((self.locale, self.output_file))

        if not po_files:
            raise DistutilsOptionError('no message catalogs found')

        domain = self.domain
        if not domain:
            domain = os.path.splitext(os.path.basename(self.input_file))[0]

        with open(self.input_file, 'rb') as infile:
            template = read_po(infile)

        for locale, filename in po_files:
            self.log.info('updating catalog %s based on %s', filename, self.input_file)
            with open(filename, 'rb') as infile:
                catalog = read_po(infile, locale=locale, domain=domain)

            catalog.update(
                template, self.no_fuzzy_matching,
                update_header_comment=self.update_header_comment
            )

            tmpname = os.path.join(os.path.dirname(filename),
                                   tempfile.gettempprefix() +
                                   os.path.basename(filename))
            try:
                with open(tmpname, 'wb') as tmpfile:
                    write_po(tmpfile, catalog,
                             ignore_obsolete=self.ignore_obsolete,
                             include_previous=self.previous, width=self.width)
            except:
                os.remove(tmpname)
                raise

            try:
                os.rename(tmpname, filename)
            except OSError:
                # We're probably on Windows, which doesn't support atomic
                # renames, at least not through Python
                # If the error is in fact due to a permissions problem, that
                # same error is going to be raised from one of the following
                # operations
                os.remove(filename)
                shutil.copy(tmpname, filename)
                os.remove(tmpname) 
Example 64
Project: myBlog   Author: adxc   File: frontend.py    MIT License 4 votes vote down vote up
def run(self):
        po_files = []
        if not self.output_file:
            if self.locale:
                po_files.append((self.locale,
                                 os.path.join(self.output_dir, self.locale,
                                              'LC_MESSAGES',
                                              self.domain + '.po')))
            else:
                for locale in os.listdir(self.output_dir):
                    po_file = os.path.join(self.output_dir, locale,
                                           'LC_MESSAGES',
                                           self.domain + '.po')
                    if os.path.exists(po_file):
                        po_files.append((locale, po_file))
        else:
            po_files.append((self.locale, self.output_file))

        if not po_files:
            raise DistutilsOptionError('no message catalogs found')

        domain = self.domain
        if not domain:
            domain = os.path.splitext(os.path.basename(self.input_file))[0]

        with open(self.input_file, 'rb') as infile:
            template = read_po(infile)

        for locale, filename in po_files:
            self.log.info('updating catalog %s based on %s', filename, self.input_file)
            with open(filename, 'rb') as infile:
                catalog = read_po(infile, locale=locale, domain=domain)

            catalog.update(
                template, self.no_fuzzy_matching,
                update_header_comment=self.update_header_comment
            )

            tmpname = os.path.join(os.path.dirname(filename),
                                   tempfile.gettempprefix() +
                                   os.path.basename(filename))
            try:
                with open(tmpname, 'wb') as tmpfile:
                    write_po(tmpfile, catalog,
                             ignore_obsolete=self.ignore_obsolete,
                             include_previous=self.previous, width=self.width)
            except:
                os.remove(tmpname)
                raise

            try:
                os.rename(tmpname, filename)
            except OSError:
                # We're probably on Windows, which doesn't support atomic
                # renames, at least not through Python
                # If the error is in fact due to a permissions problem, that
                # same error is going to be raised from one of the following
                # operations
                os.remove(filename)
                shutil.copy(tmpname, filename)
                os.remove(tmpname) 
Example 65
Project: Light_control   Author: laurent-colas   File: frontend.py    The Unlicense 4 votes vote down vote up
def run(self):
        po_files = []
        if not self.output_file:
            if self.locale:
                po_files.append((self.locale,
                                 os.path.join(self.output_dir, self.locale,
                                              'LC_MESSAGES',
                                              self.domain + '.po')))
            else:
                for locale in os.listdir(self.output_dir):
                    po_file = os.path.join(self.output_dir, locale,
                                           'LC_MESSAGES',
                                           self.domain + '.po')
                    if os.path.exists(po_file):
                        po_files.append((locale, po_file))
        else:
            po_files.append((self.locale, self.output_file))

        if not po_files:
            raise DistutilsOptionError('no message catalogs found')

        domain = self.domain
        if not domain:
            domain = os.path.splitext(os.path.basename(self.input_file))[0]

        with open(self.input_file, 'rb') as infile:
            template = read_po(infile)

        for locale, filename in po_files:
            self.log.info('updating catalog %s based on %s', filename, self.input_file)
            with open(filename, 'rb') as infile:
                catalog = read_po(infile, locale=locale, domain=domain)

            catalog.update(
                template, self.no_fuzzy_matching,
                update_header_comment=self.update_header_comment
            )

            tmpname = os.path.join(os.path.dirname(filename),
                                   tempfile.gettempprefix() +
                                   os.path.basename(filename))
            try:
                with open(tmpname, 'wb') as tmpfile:
                    write_po(tmpfile, catalog,
                             ignore_obsolete=self.ignore_obsolete,
                             include_previous=self.previous, width=self.width)
            except:
                os.remove(tmpname)
                raise

            try:
                os.rename(tmpname, filename)
            except OSError:
                # We're probably on Windows, which doesn't support atomic
                # renames, at least not through Python
                # If the error is in fact due to a permissions problem, that
                # same error is going to be raised from one of the following
                # operations
                os.remove(filename)
                shutil.copy(tmpname, filename)
                os.remove(tmpname)