Python os.replace() Examples

The following are code examples for showing how to use os.replace(). 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: blobfile   Author: cshesse   File: ops.py    The Unlicense 6 votes vote down vote up
def stat(path: str) -> Stat:
    """
    Stat a file or object representing a directory, returns a Stat object
    """
    if _is_local_path(path):
        s = os.stat(path)
        return Stat(size=s.st_size, mtime=s.st_mtime)
    elif _is_google_path(path):
        isfile, metadata = _google_isfile(path)
        if not isfile:
            raise FileNotFoundError(f"No such file: '{path}'")
        ts = time.strptime(
            metadata["updated"].replace("Z", "GMT"), "%Y-%m-%dT%H:%M:%S.%f%Z"
        )
        t = calendar.timegm(ts)
        return Stat(size=int(metadata["size"]), mtime=t)
    elif _is_azure_path(path):
        isfile, metadata = _azure_isfile(path)
        if not isfile:
            raise FileNotFoundError(f"No such file: '{path}'")
        ts = time.strptime(metadata["Last-Modified"], "%a, %d %b %Y %H:%M:%S %Z")
        t = calendar.timegm(ts)
        return Stat(size=int(metadata["Content-Length"]), mtime=t)
    else:
        raise Exception("unrecognized path") 
Example 2
Project: Restricted-WebM   Author: HelpSeeker   File: restrict.py    GNU General Public License v3.0 6 votes vote down vote up
def update(self, temp_file, out_file, enhance):
        """Update all properties during the limiting process"""
        if opts.debug:
            try:
                user = float(input("Output size in MB: "))
            except ValueError:
                # Use empty input as shortcut to end debug mode (simulate success)
                user = opts.limit

            self.last = self.temp
            self.temp = int(user * 1024**2)
        else:
            self.last = self.temp
            self.temp = os.path.getsize(temp_file)

        if enhance:
            if self.out < self.temp <= int(opts.limit * 1024**2):
                self.out = self.temp
                if not opts.debug:
                    os.replace(temp_file, out_file)
        else:
            if not self.out or self.temp < self.out:
                self.out = self.temp
                if not opts.debug:
                    os.replace(temp_file, out_file) 
Example 3
Project: pyuavcan   Author: UAVCAN   File: node.py    MIT License 6 votes vote down vote up
def _register_emitted_transfer_id_map_save_at_exit(presentation: pyuavcan.presentation.Presentation) -> None:
        # We MUST sample the configuration early because if this is a redundant transport it may reset its
        # reported descriptor and local node-ID back to default after close().
        local_node_id = presentation.transport.local_node_id
        descriptor = presentation.transport.descriptor

        def do_save_at_exit() -> None:
            if local_node_id is not None:
                file_path = _get_emitted_transfer_id_file_path(local_node_id, descriptor)
                tmp_path = f'{file_path}.{os.getpid()}.{time.time_ns()}.tmp'
                _logger.debug('Emitted TID map save: %s --> %s', tmp_path, file_path)
                with open(tmp_path, 'wb') as f:
                    pickle.dump(presentation.emitted_transfer_id_map, f)
                # We use replace for compatibility reasons. On POSIX, a call to rename() will be made, which is
                # guaranteed to be atomic. On Windows this may fall back to non-atomic copy, which is still
                # acceptable for us here. If the file ends up being damaged, we'll simply ignore it at next startup.
                os.replace(tmp_path, file_path)
                try:
                    os.unlink(tmp_path)
                except OSError:
                    pass
            else:
                _logger.debug('Emitted TID map NOT saved because the transport instance is anonymous')

        atexit.register(do_save_at_exit) 
Example 4
Project: bob   Author: BobBuildTool   File: common.py    GNU General Public License v3.0 6 votes vote down vote up
def updateFile(self, name, content, encoding=None, newline=None):
        newName = name+".new"
        oldName = name+".old"
        with open(newName, "w", encoding=encoding, newline=newline) as f:
            f.write(content)
        with open(newName, "rb") as f:
            newContent = f.read()
        try:
            with open(oldName, "rb") as f:
                oldContent = f.read()
        except OSError:
            oldContent = None

        if oldContent != newContent:
            os.replace(newName, name)
            with open(oldName, "wb") as f:
                f.write(newContent)
        else:
            os.remove(newName) 
Example 5
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: utils.py    Apache License 2.0 5 votes vote down vote up
def _replace_atomic(src, dst):
        """Implement atomic os.replace with linux and OSX. Internal use only"""
        try:
            os.rename(src, dst)
        except OSError:
            try:
                os.remove(src)
            except OSError:
                pass
            finally:
                raise OSError(
                    'Moving downloaded temp file - {}, to {} failed. \
                    Please retry the download.'.format(src, dst)) 
Example 6
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: utils.py    Apache License 2.0 5 votes vote down vote up
def _replace_atomic(src, dst):
        """Implement atomic os.replace with windows.
        refer to https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-movefileexw
        The function fails when one of the process(copy, flush, delete) fails.
        Internal use only"""
        _handle_errors(ctypes.windll.kernel32.MoveFileExW(
            _str_to_unicode(src), _str_to_unicode(dst),
            _windows_default_flags | _MOVEFILE_REPLACE_EXISTING
        ), src) 
Example 7
Project: blobfile   Author: cshesse   File: ops.py    The Unlicense 5 votes vote down vote up
def join(a: str, *args: str) -> str:
    """
    Join file paths, if a path is an absolute path, it will replace the entire path component of previous paths
    """
    out = a
    for b in args:
        out = _join2(out, b)
    return out 
Example 8
Project: surreptitious   Author: neuroFuzz   File: queue.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def atomic_rename(src, dst):
    try:
        os.replace(src, dst)
    except (AttributeError,OSError):  # python < 3.3
        import sys

        if sys.platform == 'win32':
            import ctypes

            if sys.version_info[0] == 2:
                _str = unicode
                _bytes = str
            else:
                _str = str
                _bytes = bytes

            if isinstance(src, _str) and isinstance(dst, _str):
                MoveFileEx = ctypes.windll.kernel32.MoveFileExW
            elif isinstance(src, _bytes) and isinstance(dst, _bytes):
                MoveFileEx = ctypes.windll.kernel32.MoveFileExA
            else:
                raise ValueError("Both args must be bytes or unicode.")

            MOVEFILE_REPLACE_EXISTING = 0x1

            if not MoveFileEx(src, dst, MOVEFILE_REPLACE_EXISTING):
                errno = ctypes.GetLastError()
                strerror = os.strerror(errno)
                raise WindowsError(errno, strerror)

        else:
            #os.rename(src, dst)
            shutil.move(src, dst) 
Example 9
Project: NiujiaoDebugger   Author: MrSrc   File: pathlib.py    GNU General Public License v3.0 5 votes vote down vote up
def parse_parts(self, parts):
        parsed = []
        sep = self.sep
        altsep = self.altsep
        drv = root = ''
        it = reversed(parts)
        for part in it:
            if not part:
                continue
            if altsep:
                part = part.replace(altsep, sep)
            drv, root, rel = self.splitroot(part)
            if sep in rel:
                for x in reversed(rel.split(sep)):
                    if x and x != '.':
                        parsed.append(sys.intern(x))
            else:
                if rel and rel != '.':
                    parsed.append(sys.intern(rel))
            if drv or root:
                if not drv:
                    # If no drive is present, try to find one in the previous
                    # parts. This makes the result of parsing e.g.
                    # ("C:", "/", "a") reasonably intuitive.
                    for part in it:
                        if not part:
                            continue
                        if altsep:
                            part = part.replace(altsep, sep)
                        drv = self.splitroot(part)[0]
                        if drv:
                            break
                break
        if drv or root:
            parsed.append(drv + root)
        parsed.reverse()
        return drv, root, parsed 
Example 10
Project: NiujiaoDebugger   Author: MrSrc   File: pathlib.py    GNU General Public License v3.0 5 votes vote down vote up
def as_posix(self):
        """Return the string representation of the path with forward (/)
        slashes."""
        f = self._flavour
        return str(self).replace(f.sep, '/') 
Example 11
Project: NiujiaoDebugger   Author: MrSrc   File: pathlib.py    GNU General Public License v3.0 5 votes vote down vote up
def replace(self, target):
        """
        Rename this path to the given path, clobbering the existing
        destination if it exists.
        """
        if self._closed:
            self._raise_closed()
        self._accessor.replace(self, target) 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    GNU General Public License v3.0 5 votes vote down vote up
def test_replace(self):
        TESTFN2 = support.TESTFN + ".2"
        self.addCleanup(support.unlink, support.TESTFN)
        self.addCleanup(support.unlink, TESTFN2)

        create_file(support.TESTFN, b"1")
        create_file(TESTFN2, b"2")

        os.replace(support.TESTFN, TESTFN2)
        self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
        with open(TESTFN2, 'r') as f:
            self.assertEqual(f.read(), "1") 
Example 13
Project: NiujiaoDebugger   Author: MrSrc   File: clinic.py    GNU General Public License v3.0 5 votes vote down vote up
def quoted_for_c_string(s):
    for old, new in (
        ('\\', '\\\\'), # must be first!
        ('"', '\\"'),
        ("'", "\\'"),
        ):
        s = s.replace(old, new)
    return s 
Example 14
Project: NiujiaoDebugger   Author: MrSrc   File: clinic.py    GNU General Public License v3.0 5 votes vote down vote up
def parse_file(filename, *, force=False, verify=True, output=None, encoding='utf-8'):
    extension = os.path.splitext(filename)[1][1:]
    if not extension:
        fail("Can't extract file type for file " + repr(filename))

    try:
        language = extensions[extension](filename)
    except KeyError:
        fail("Can't identify file type for file " + repr(filename))

    with open(filename, 'r', encoding=encoding) as f:
        raw = f.read()

    # exit quickly if there are no clinic markers in the file
    find_start_re = BlockParser("", language).find_start_re
    if not find_start_re.search(raw):
        return

    clinic = Clinic(language, force=force, verify=verify, filename=filename)
    cooked = clinic.parse(raw)
    if (cooked == raw) and not force:
        return

    directory = os.path.dirname(filename) or '.'

    with tempfile.TemporaryDirectory(prefix="clinic", dir=directory) as tmpdir:
        bytes = cooked.encode(encoding)
        tmpfilename = os.path.join(tmpdir, os.path.basename(filename))
        with open(tmpfilename, "wb") as f:
            f.write(bytes)
        os.replace(tmpfilename, output or filename) 
Example 15
Project: NiujiaoDebugger   Author: MrSrc   File: update_file.py    GNU General Public License v3.0 5 votes vote down vote up
def main(old_path, new_path):
    with open(old_path, 'rb') as f:
        old_contents = f.read()
    with open(new_path, 'rb') as f:
        new_contents = f.read()
    if old_contents != new_contents:
        os.replace(new_path, old_path)
    else:
        os.unlink(new_path) 
Example 16
Project: Health-Checker   Author: KriAga   File: _compat.py    MIT License 5 votes vote down vote up
def _make_text_stream(stream, encoding, errors,
                      force_readable=False, force_writable=False):
    if encoding is None:
        encoding = get_best_encoding(stream)
    if errors is None:
        errors = 'replace'
    return _NonClosingTextIOWrapper(stream, encoding, errors,
                                    line_buffering=True,
                                    force_readable=force_readable,
                                    force_writable=force_writable) 
Example 17
Project: Health-Checker   Author: KriAga   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        return value 
Example 18
Project: Health-Checker   Author: KriAga   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_reader(text_reader, encoding, errors,
                                   force_readable=False):
        if _is_binary_reader(text_reader, False):
            binary_reader = text_reader
        else:
            # If there is no target encoding set, we need to verify that the
            # reader is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_reader):
                return text_reader

            if _is_compatible_text_stream(text_reader, encoding, errors):
                return text_reader

            # If the reader has no encoding, we try to find the underlying
            # binary reader for it.  If that fails because the environment is
            # misconfigured, we silently go with the same reader because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_reader = _find_binary_reader(text_reader)
            if binary_reader is None:
                return text_reader

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_reader, encoding, errors,
                                 force_readable=force_readable) 
Example 19
Project: Health-Checker   Author: KriAga   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_writer(text_writer, encoding, errors,
                                   force_writable=False):
        if _is_binary_writer(text_writer, False):
            binary_writer = text_writer
        else:
            # If there is no target encoding set, we need to verify that the
            # writer is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_writer):
                return text_writer

            if _is_compatible_text_stream(text_writer, encoding, errors):
                return text_writer

            # If the writer has no encoding, we try to find the underlying
            # binary writer for it.  If that fails because the environment is
            # misconfigured, we silently go with the same writer because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_writer = _find_binary_writer(text_writer)
            if binary_writer is None:
                return text_writer

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_writer, encoding, errors,
                                 force_writable=force_writable) 
Example 20
Project: Health-Checker   Author: KriAga   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        else:
            value = value.encode('utf-8', 'surrogateescape') \
                .decode('utf-8', 'replace')
        return value 
Example 21
Project: recruit   Author: Frank-qlu   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def _make_text_stream(stream, encoding, errors,
                      force_readable=False, force_writable=False):
    if encoding is None:
        encoding = get_best_encoding(stream)
    if errors is None:
        errors = 'replace'
    return _NonClosingTextIOWrapper(stream, encoding, errors,
                                    line_buffering=True,
                                    force_readable=force_readable,
                                    force_writable=force_writable) 
Example 22
Project: recruit   Author: Frank-qlu   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        return value 
Example 23
Project: recruit   Author: Frank-qlu   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def _force_correct_text_reader(text_reader, encoding, errors,
                                   force_readable=False):
        if _is_binary_reader(text_reader, False):
            binary_reader = text_reader
        else:
            # If there is no target encoding set, we need to verify that the
            # reader is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_reader):
                return text_reader

            if _is_compatible_text_stream(text_reader, encoding, errors):
                return text_reader

            # If the reader has no encoding, we try to find the underlying
            # binary reader for it.  If that fails because the environment is
            # misconfigured, we silently go with the same reader because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_reader = _find_binary_reader(text_reader)
            if binary_reader is None:
                return text_reader

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_reader, encoding, errors,
                                 force_readable=force_readable) 
Example 24
Project: recruit   Author: Frank-qlu   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def _force_correct_text_writer(text_writer, encoding, errors,
                                   force_writable=False):
        if _is_binary_writer(text_writer, False):
            binary_writer = text_writer
        else:
            # If there is no target encoding set, we need to verify that the
            # writer is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_writer):
                return text_writer

            if _is_compatible_text_stream(text_writer, encoding, errors):
                return text_writer

            # If the writer has no encoding, we try to find the underlying
            # binary writer for it.  If that fails because the environment is
            # misconfigured, we silently go with the same writer because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_writer = _find_binary_writer(text_writer)
            if binary_writer is None:
                return text_writer

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_writer, encoding, errors,
                                 force_writable=force_writable) 
Example 25
Project: recruit   Author: Frank-qlu   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        else:
            value = value.encode('utf-8', 'surrogateescape') \
                .decode('utf-8', 'replace')
        return value 
Example 26
Project: jbox   Author: jpush   File: _compat.py    MIT License 5 votes vote down vote up
def _make_text_stream(stream, encoding, errors):
    if encoding is None:
        encoding = get_best_encoding(stream)
    if errors is None:
        errors = 'replace'
    return _NonClosingTextIOWrapper(stream, encoding, errors,
                                    line_buffering=True) 
Example 27
Project: jbox   Author: jpush   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        return value 
Example 28
Project: jbox   Author: jpush   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_reader(text_reader, encoding, errors):
        if _is_binary_reader(text_reader, False):
            binary_reader = text_reader
        else:
            # If there is no target encoding set, we need to verify that the
            # reader is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_reader):
                return text_reader

            if _is_compatible_text_stream(text_reader, encoding, errors):
                return text_reader

            # If the reader has no encoding, we try to find the underlying
            # binary reader for it.  If that fails because the environment is
            # misconfigured, we silently go with the same reader because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_reader = _find_binary_reader(text_reader)
            if binary_reader is None:
                return text_reader

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_reader, encoding, errors) 
Example 29
Project: jbox   Author: jpush   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_writer(text_writer, encoding, errors):
        if _is_binary_writer(text_writer, False):
            binary_writer = text_writer
        else:
            # If there is no target encoding set, we need to verify that the
            # writer is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_writer):
                return text_writer

            if _is_compatible_text_stream(text_writer, encoding, errors):
                return text_writer

            # If the writer has no encoding, we try to find the underlying
            # binary writer for it.  If that fails because the environment is
            # misconfigured, we silently go with the same writer because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_writer = _find_binary_writer(text_writer)
            if binary_writer is None:
                return text_writer

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_writer, encoding, errors) 
Example 30
Project: jbox   Author: jpush   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        else:
            value = value.encode('utf-8', 'surrogateescape') \
                .decode('utf-8', 'replace')
        return value 
Example 31
Project: Alexa-Ecovacs   Author: EtienneMD   File: _compat.py    MIT License 5 votes vote down vote up
def _make_text_stream(stream, encoding, errors):
    if encoding is None:
        encoding = get_best_encoding(stream)
    if errors is None:
        errors = 'replace'
    return _NonClosingTextIOWrapper(stream, encoding, errors,
                                    line_buffering=True) 
Example 32
Project: Alexa-Ecovacs   Author: EtienneMD   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        return value 
Example 33
Project: Alexa-Ecovacs   Author: EtienneMD   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_reader(text_reader, encoding, errors):
        if _is_binary_reader(text_reader, False):
            binary_reader = text_reader
        else:
            # If there is no target encoding set, we need to verify that the
            # reader is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_reader):
                return text_reader

            if _is_compatible_text_stream(text_reader, encoding, errors):
                return text_reader

            # If the reader has no encoding, we try to find the underlying
            # binary reader for it.  If that fails because the environment is
            # misconfigured, we silently go with the same reader because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_reader = _find_binary_reader(text_reader)
            if binary_reader is None:
                return text_reader

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_reader, encoding, errors) 
Example 34
Project: Alexa-Ecovacs   Author: EtienneMD   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_writer(text_writer, encoding, errors):
        if _is_binary_writer(text_writer, False):
            binary_writer = text_writer
        else:
            # If there is no target encoding set, we need to verify that the
            # writer is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_writer):
                return text_writer

            if _is_compatible_text_stream(text_writer, encoding, errors):
                return text_writer

            # If the writer has no encoding, we try to find the underlying
            # binary writer for it.  If that fails because the environment is
            # misconfigured, we silently go with the same writer because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_writer = _find_binary_writer(text_writer)
            if binary_writer is None:
                return text_writer

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_writer, encoding, errors) 
Example 35
Project: Alexa-Ecovacs   Author: EtienneMD   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        else:
            value = value.encode('utf-8', 'surrogateescape') \
                .decode('utf-8', 'replace')
        return value 
Example 36
Project: crystals   Author: LaurentRDC   File: get_cifs.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download(name, cod_id):
    """
    Parameters
    ----------
    name : str
        Name of the structure to download
    cod_id : str or int
        Crystallography Open Database ID of the structure.
    """
    path = CODParser.download_cif(
        DOWNLOAD_DIR, num=int(cod_id), revision=None, overwrite=True
    )
    os.replace(path, path.parent / f"{name}.cif")
    print(f"Downloaded ID: {cod_id}".ljust(20), f"| {name} ") 
Example 37
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def _make_text_stream(stream, encoding, errors):
    if encoding is None:
        encoding = get_best_encoding(stream)
    if errors is None:
        errors = 'replace'
    return _NonClosingTextIOWrapper(stream, encoding, errors,
                                    line_buffering=True) 
Example 38
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        return value 
Example 39
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_reader(text_reader, encoding, errors):
        if _is_binary_reader(text_reader, False):
            binary_reader = text_reader
        else:
            # If there is no target encoding set, we need to verify that the
            # reader is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_reader):
                return text_reader

            if _is_compatible_text_stream(text_reader, encoding, errors):
                return text_reader

            # If the reader has no encoding, we try to find the underlying
            # binary reader for it.  If that fails because the environment is
            # misconfigured, we silently go with the same reader because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_reader = _find_binary_reader(text_reader)
            if binary_reader is None:
                return text_reader

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_reader, encoding, errors) 
Example 40
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_writer(text_writer, encoding, errors):
        if _is_binary_writer(text_writer, False):
            binary_writer = text_writer
        else:
            # If there is no target encoding set, we need to verify that the
            # writer is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_writer):
                return text_writer

            if _is_compatible_text_stream(text_writer, encoding, errors):
                return text_writer

            # If the writer has no encoding, we try to find the underlying
            # binary writer for it.  If that fails because the environment is
            # misconfigured, we silently go with the same writer because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_writer = _find_binary_writer(text_writer)
            if binary_writer is None:
                return text_writer

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_writer, encoding, errors) 
Example 41
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        else:
            value = value.encode('utf-8', 'surrogateescape') \
                .decode('utf-8', 'replace')
        return value 
Example 42
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def _make_text_stream(stream, encoding, errors):
    if encoding is None:
        encoding = get_best_encoding(stream)
    if errors is None:
        errors = 'replace'
    return _NonClosingTextIOWrapper(stream, encoding, errors,
                                    line_buffering=True) 
Example 43
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        return value 
Example 44
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_reader(text_reader, encoding, errors):
        if _is_binary_reader(text_reader, False):
            binary_reader = text_reader
        else:
            # If there is no target encoding set, we need to verify that the
            # reader is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_reader):
                return text_reader

            if _is_compatible_text_stream(text_reader, encoding, errors):
                return text_reader

            # If the reader has no encoding, we try to find the underlying
            # binary reader for it.  If that fails because the environment is
            # misconfigured, we silently go with the same reader because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_reader = _find_binary_reader(text_reader)
            if binary_reader is None:
                return text_reader

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_reader, encoding, errors) 
Example 45
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def _force_correct_text_writer(text_writer, encoding, errors):
        if _is_binary_writer(text_writer, False):
            binary_writer = text_writer
        else:
            # If there is no target encoding set, we need to verify that the
            # writer is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_writer):
                return text_writer

            if _is_compatible_text_stream(text_writer, encoding, errors):
                return text_writer

            # If the writer has no encoding, we try to find the underlying
            # binary writer for it.  If that fails because the environment is
            # misconfigured, we silently go with the same writer because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_writer = _find_binary_writer(text_writer)
            if binary_writer is None:
                return text_writer

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_writer, encoding, errors) 
Example 46
Project: Mahjong-Solitaire   Author: MEASHY   File: _compat.py    MIT License 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        else:
            value = value.encode('utf-8', 'surrogateescape') \
                .decode('utf-8', 'replace')
        return value 
Example 47
Project: oa_qian   Author: sunqb   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def _make_text_stream(stream, encoding, errors):
    if encoding is None:
        encoding = get_best_encoding(stream)
    if errors is None:
        errors = 'replace'
    return _NonClosingTextIOWrapper(stream, encoding, errors,
                                    line_buffering=True) 
Example 48
Project: oa_qian   Author: sunqb   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def filename_to_ui(value):
        if isinstance(value, bytes):
            value = value.decode(get_filesystem_encoding(), 'replace')
        return value 
Example 49
Project: oa_qian   Author: sunqb   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def _force_correct_text_reader(text_reader, encoding, errors):
        if _is_binary_reader(text_reader, False):
            binary_reader = text_reader
        else:
            # If there is no target encoding set, we need to verify that the
            # reader is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_reader):
                return text_reader

            if _is_compatible_text_stream(text_reader, encoding, errors):
                return text_reader

            # If the reader has no encoding, we try to find the underlying
            # binary reader for it.  If that fails because the environment is
            # misconfigured, we silently go with the same reader because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_reader = _find_binary_reader(text_reader)
            if binary_reader is None:
                return text_reader

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_reader, encoding, errors) 
Example 50
Project: oa_qian   Author: sunqb   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def _force_correct_text_writer(text_writer, encoding, errors):
        if _is_binary_writer(text_writer, False):
            binary_writer = text_writer
        else:
            # If there is no target encoding set, we need to verify that the
            # writer is not actually misconfigured.
            if encoding is None and not _stream_is_misconfigured(text_writer):
                return text_writer

            if _is_compatible_text_stream(text_writer, encoding, errors):
                return text_writer

            # If the writer has no encoding, we try to find the underlying
            # binary writer for it.  If that fails because the environment is
            # misconfigured, we silently go with the same writer because this
            # is too common to happen.  In that case, mojibake is better than
            # exceptions.
            binary_writer = _find_binary_writer(text_writer)
            if binary_writer is None:
                return text_writer

        # At this point, we default the errors to replace instead of strict
        # because nobody handles those errors anyways and at this point
        # we're so fundamentally fucked that nothing can repair it.
        if errors is None:
            errors = 'replace'
        return _make_text_stream(binary_writer, encoding, errors)