Python os.fsencode() Examples

The following are 30 code examples of os.fsencode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: misc.py    From jbox with MIT License 6 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #2
Source File: util.py    From renpy-shader with MIT License 6 votes vote down vote up
def find_library(name):
            ename = re.escape(name)
            expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
            expr = os.fsencode(expr)

            try:
                proc = subprocess.Popen(('/sbin/ldconfig', '-r'),
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.DEVNULL)
            except OSError:  # E.g. command not found
                data = b''
            else:
                with proc:
                    data = proc.stdout.read()

            res = re.findall(expr, data)
            if not res:
                return _get_soname(_findLib_gcc(name))
            res.sort(key=_num_version)
            return os.fsdecode(res[-1]) 
Example #3
Source File: tempfile.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _sanitize_params(prefix, suffix, dir):
    """Common parameter processing for most APIs in this module."""
    output_type = _infer_return_type(prefix, suffix, dir)
    if suffix is None:
        suffix = output_type()
    if prefix is None:
        if output_type is str:
            prefix = template
        else:
            prefix = _os.fsencode(template)
    if dir is None:
        if output_type is str:
            dir = gettempdir()
        else:
            dir = gettempdirb()
    return prefix, suffix, dir, output_type 
Example #4
Source File: tempfile.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _sanitize_params(prefix, suffix, dir):
    """Common parameter processing for most APIs in this module."""
    output_type = _infer_return_type(prefix, suffix, dir)
    if suffix is None:
        suffix = output_type()
    if prefix is None:
        if output_type is str:
            prefix = template
        else:
            prefix = _os.fsencode(template)
    if dir is None:
        if output_type is str:
            dir = gettempdir()
        else:
            dir = gettempdirb()
    return prefix, suffix, dir, output_type 
Example #5
Source File: reflink.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _update_loopdev_sizes(img):
    ''' Resolve img; update the size of loop devices backed by it. '''
    needle = os.fsencode(os.path.realpath(img)) + b'\n'
    for sys_path in glob.iglob('/sys/block/loop[0-9]*/loop/backing_file'):
        try:
            with open(sys_path, 'rb') as sys_io:
                if sys_io.read() != needle:
                    continue
        except FileNotFoundError:
            continue
        with open('/dev/' + sys_path.split('/')[3], 'rb') as dev_io:
            fcntl.ioctl(dev_io.fileno(), LOOP_SET_CAPACITY) 
Example #6
Source File: compat.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #7
Source File: mmd.py    From Blender-Metaverse-Addon with GNU General Public License v3.0 5 votes vote down vote up
def purge_string(string):
    try:
        str_bytes = os.fsencode(string)
        return str_bytes.decode("utf-8", "replace")
    except UnicodeEncodeError:
        print("Could not purge string", string)
        return string 
Example #8
Source File: compat.py    From hacktoberfest2018 with GNU General Public License v3.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #9
Source File: misc.py    From hacktoberfest2018 with GNU General Public License v3.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #10
Source File: compare.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, orig, dest):
        if not self._proc:
            self._stdout = TemporaryFile()
            self._proc = subprocess.Popen(
                [matplotlib.checkdep_ghostscript.executable,
                 "-dNOPAUSE", "-sDEVICE=png16m"],
                # As far as I can see, ghostscript never outputs to stderr.
                stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            try:
                self._read_until(b"\nGS")
            except _ConverterError:
                raise OSError("Failed to start Ghostscript")

        def encode_and_escape(name):
            return (os.fsencode(name)
                    .replace(b"\\", b"\\\\")
                    .replace(b"(", br"\(")
                    .replace(b")", br"\)"))

        self._proc.stdin.write(
            b"<< /OutputFile ("
            + encode_and_escape(dest)
            + b") >> setpagedevice ("
            + encode_and_escape(orig)
            + b") run flush\n")
        self._proc.stdin.flush()
        # GS> if nothing left on the stack; GS<n> if n items left on the stack.
        err = self._read_until(b"GS")
        stack = self._read_until(b">")
        if stack or not os.path.exists(dest):
            stack_size = int(stack[1:]) if stack else 0
            self._proc.stdin.write(b"pop\n" * stack_size)
            # Using the systemencoding should at least get the filenames right.
            raise ImageComparisonFailure(
                (err + b"GS" + stack + b">")
                .decode(sys.getfilesystemencoding(), "replace")) 
Example #11
Source File: exiftool.py    From osxphotos with MIT License 5 votes vote down vote up
def run_commands(self, *commands, no_file=False):
        """ run commands in the exiftool process and return result 
            no_file: (bool) do not pass the filename to exiftool (default=False)
                     by default, all commands will be run against self.file
                     use no_file=True to run a command without passing the filename """
        if not (hasattr(self, "_process") and self._process):
            raise ValueError("exiftool process is not running")

        if not commands:
            raise TypeError("must provide one or more command to run")

        filename = os.fsencode(self.file) if not no_file else b""
        command_str = (
            b"\n".join([c.encode("utf-8") for c in commands])
            + b"\n"
            + filename
            + b"\n"
            + b"-execute\n"
        )

        if _debug():
            logging.debug(command_str)

        # send the command
        self._process.stdin.write(command_str)
        self._process.stdin.flush()

        # read the output
        output = b""
        while EXIFTOOL_STAYOPEN_EOF not in str(output):
            output += self._process.stdout.readline().strip()
        return output[:-EXIFTOOL_STAYOPEN_EOF_LEN] 
Example #12
Source File: compare.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __call__(self, orig, dest):
        if not self._proc:
            self._stdout = TemporaryFile()
            self._proc = subprocess.Popen(
                [matplotlib.checkdep_ghostscript.executable,
                 "-dNOPAUSE", "-sDEVICE=png16m"],
                # As far as I can see, ghostscript never outputs to stderr.
                stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            try:
                self._read_until(b"\nGS")
            except _ConverterError:
                raise OSError("Failed to start Ghostscript")

        def encode_and_escape(name):
            return (os.fsencode(name)
                    .replace(b"\\", b"\\\\")
                    .replace(b"(", br"\(")
                    .replace(b")", br"\)"))

        self._proc.stdin.write(
            b"<< /OutputFile ("
            + encode_and_escape(dest)
            + b") >> setpagedevice ("
            + encode_and_escape(orig)
            + b") run flush\n")
        self._proc.stdin.flush()
        # GS> if nothing left on the stack; GS<n> if n items left on the stack.
        err = self._read_until(b"GS")
        stack = self._read_until(b">")
        if stack or not os.path.exists(dest):
            stack_size = int(stack[1:]) if stack else 0
            self._proc.stdin.write(b"pop\n" * stack_size)
            # Using the systemencoding should at least get the filenames right.
            raise ImageComparisonFailure(
                (err + b"GS" + stack + b">")
                .decode(sys.getfilesystemencoding(), "replace")) 
Example #13
Source File: compat.py    From hacktoberfest2018 with GNU General Public License v3.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #14
Source File: compat.py    From pipenv with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #15
Source File: misc.py    From pipenv with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #16
Source File: compat.py    From pipenv with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #17
Source File: misc.py    From pipenv with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #18
Source File: misc.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #19
Source File: compat.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #20
Source File: misc.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #21
Source File: compat.py    From pex with Apache License 2.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #22
Source File: misc.py    From pex with Apache License 2.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #23
Source File: compat.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #24
Source File: misc.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #25
Source File: compat.py    From anpr with Creative Commons Attribution 4.0 International 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #26
Source File: misc.py    From anpr with Creative Commons Attribution 4.0 International 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #27
Source File: compat.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #28
Source File: misc.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, str):
            return filename.encode(sys.getfilesystemencoding())
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #29
Source File: compat.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__) 
Example #30
Source File: compat.py    From oss-ftp with MIT License 5 votes vote down vote up
def fsencode(filename):
        if isinstance(filename, bytes):
            return filename
        elif isinstance(filename, text_type):
            return filename.encode(_fsencoding, _fserrors)
        else:
            raise TypeError("expect bytes or str, not %s" %
                            type(filename).__name__)