Python os.fsencode() Examples

The following are code examples for showing how to use os.fsencode(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: zippy   Author: securesystemslab   File: test_subprocess.py    (license) View Source Project 6 votes vote down vote up
def test_bytes_program(self):
        abs_program = os.fsencode(sys.executable)
        path, program = os.path.split(sys.executable)
        program = os.fsencode(program)

        # absolute bytes path
        exitcode = subprocess.call([abs_program, "-c", "pass"])
        self.assertEqual(exitcode, 0)

        # bytes program, unicode PATH
        env = os.environ.copy()
        env["PATH"] = path
        exitcode = subprocess.call([program, "-c", "pass"], env=env)
        self.assertEqual(exitcode, 0)

        # bytes program, bytes PATH
        envb = os.environb.copy()
        envb[b"PATH"] = os.fsencode(path)
        exitcode = subprocess.call([program, "-c", "pass"], env=envb)
        self.assertEqual(exitcode, 0) 
Example 2
Project: web_ctp   Author: molebot   File: test_os.py    (license) View Source Project 6 votes vote down vote up
def test_deprecated(self):
        import nt
        filename = os.fsencode(support.TESTFN)
        with warnings.catch_warnings():
            warnings.simplefilter("error", DeprecationWarning)
            for func, *args in (
                (nt._getfullpathname, filename),
                (nt._isdir, filename),
                (os.access, filename, os.R_OK),
                (os.chdir, filename),
                (os.chmod, filename, 0o777),
                (os.getcwdb,),
                (os.link, filename, filename),
                (os.listdir, filename),
                (os.lstat, filename),
                (os.mkdir, filename),
                (os.open, filename, os.O_RDONLY),
                (os.rename, filename, filename),
                (os.rmdir, filename),
                (os.startfile, filename),
                (os.stat, filename),
                (os.unlink, filename),
                (os.utime, filename),
            ):
                self.assertRaises(DeprecationWarning, func, *args) 
Example 3
Project: web_ctp   Author: molebot   File: test_glob.py    (license) View Source Project 6 votes vote down vote up
def test_glob_bytes_directory_with_trailing_slash(self):
        # Same as test_glob_directory_with_trailing_slash, but with a
        # bytes argument.
        res = glob.glob(os.fsencode(self.norm('Z*Z') + os.sep))
        self.assertEqual(res, [])
        res = glob.glob(os.fsencode(self.norm('ZZZ') + os.sep))
        self.assertEqual(res, [])
        res = glob.glob(os.fsencode(self.norm('aa*') + os.sep))
        self.assertEqual(len(res), 2)
        # either of these results is reasonable
        self.assertIn(set(res), [
                      {os.fsencode(self.norm('aaa')),
                       os.fsencode(self.norm('aab'))},
                      {os.fsencode(self.norm('aaa') + os.sep),
                       os.fsencode(self.norm('aab') + os.sep)},
                      ]) 
Example 4
Project: web_ctp   Author: molebot   File: test_subprocess.py    (license) View Source Project 6 votes vote down vote up
def test_bytes_program(self):
        abs_program = os.fsencode(sys.executable)
        path, program = os.path.split(sys.executable)
        program = os.fsencode(program)

        # absolute bytes path
        exitcode = subprocess.call([abs_program, "-c", "pass"])
        self.assertEqual(exitcode, 0)

        # absolute bytes path as a string
        cmd = b"'" + abs_program + b"' -c pass"
        exitcode = subprocess.call(cmd, shell=True)
        self.assertEqual(exitcode, 0)

        # bytes program, unicode PATH
        env = os.environ.copy()
        env["PATH"] = path
        exitcode = subprocess.call([program, "-c", "pass"], env=env)
        self.assertEqual(exitcode, 0)

        # bytes program, bytes PATH
        envb = os.environb.copy()
        envb[b"PATH"] = os.fsencode(path)
        exitcode = subprocess.call([program, "-c", "pass"], env=envb)
        self.assertEqual(exitcode, 0) 
Example 5
Project: web_ctp   Author: molebot   File: test_genericpath.py    (license) View Source Project 6 votes vote down vote up
def test_abspath_issue3426(self):
        # Check that abspath returns unicode when the arg is unicode
        # with both ASCII and non-ASCII cwds.
        abspath = self.pathmodule.abspath
        for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
            self.assertIsInstance(abspath(path), str)

        unicwd = '\xe7w\xf0'
        try:
            os.fsencode(unicwd)
        except (AttributeError, UnicodeEncodeError):
            # FS encoding is probably ASCII
            pass
        else:
            with support.temp_cwd(unicwd):
                for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
                    self.assertIsInstance(abspath(path), str) 
Example 6
Project: python-   Author: secondtonone1   File: misc.py    (license) View Source Project 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 7
Project: python-   Author: secondtonone1   File: compat.py    (license) View Source Project 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 8
Project: python-   Author: secondtonone1   File: tempfile.py    (license) View Source Project 5 votes vote down vote up
def _mkstemp_inner(dir, pre, suf, flags, output_type):
    """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""

    names = _get_candidate_names()
    if output_type is bytes:
        names = map(_os.fsencode, names)

    for seq in range(TMP_MAX):
        name = next(names)
        file = _os.path.join(dir, pre + name + suf)
        try:
            fd = _os.open(file, flags, 0o600)
        except FileExistsError:
            continue    # try again
        except PermissionError:
            # This exception is thrown when a directory with the chosen name
            # already exists on windows.
            if (_os.name == 'nt' and _os.path.isdir(dir) and
                _os.access(dir, _os.W_OK)):
                continue
            else:
                raise
        return (fd, _os.path.abspath(file))

    raise FileExistsError(_errno.EEXIST,
                          "No usable temporary file name found")


# User visible interfaces. 
Example 9
Project: python-   Author: secondtonone1   File: tempfile.py    (license) View Source Project 5 votes vote down vote up
def gettempprefixb():
    """The default prefix for temporary directories as bytes."""
    return _os.fsencode(gettempprefix()) 
Example 10
Project: python-   Author: secondtonone1   File: tempfile.py    (license) View Source Project 5 votes vote down vote up
def gettempdirb():
    """A bytes version of tempfile.gettempdir()."""
    return _os.fsencode(gettempdir()) 
Example 11
Project: python-   Author: secondtonone1   File: tempfile.py    (license) View Source Project 5 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """User-callable function to create and return a unique temporary
    directory.  The return value is the pathname of the directory.

    Arguments are as for mkstemp, except that the 'text' argument is
    not accepted.

    The directory is readable, writable, and searchable only by the
    creating user.

    Caller is responsible for deleting the directory when done with it.
    """

    prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)

    names = _get_candidate_names()
    if output_type is bytes:
        names = map(_os.fsencode, names)

    for seq in range(TMP_MAX):
        name = next(names)
        file = _os.path.join(dir, prefix + name + suffix)
        try:
            _os.mkdir(file, 0o700)
        except FileExistsError:
            continue    # try again
        except PermissionError:
            # This exception is thrown when a directory with the chosen name
            # already exists on windows.
            if (_os.name == 'nt' and _os.path.isdir(dir) and
                _os.access(dir, _os.W_OK)):
                continue
            else:
                raise
        return file

    raise FileExistsError(_errno.EEXIST,
                          "No usable temporary directory name found") 
Example 12
Project: my-first-blog   Author: AnkurBegining   File: misc.py    (license) View Source Project 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 13
Project: my-first-blog   Author: AnkurBegining   File: compat.py    (license) View Source Project 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
Project: whatstyle   Author: mikr   File: outtakes.py    (MIT License) View Source Project 5 votes vote down vote up
def bytestr(text):
    if isinstance(text, binary_type):
        return text
    try:
        return text.encode('utf-8')
    except UnicodeEncodeError:
        if HAS_FSCODEC:
            return os.fsencode(text)
        raise 
Example 15
Project: whatstyle   Author: mikr   File: whatstyle.py    (MIT License) View Source Project 5 votes vote down vote up
def bytestr(text):
    # type: (Union[str, bytes]) -> bytes
    if isinstance(text, binary_type):
        return text
    try:
        return text.encode('utf-8')
    except UnicodeEncodeError:
        if HAS_FSCODEC:
            return os.fsencode(text)
        raise 
Example 16
Project: whatstyle   Author: mikr   File: whatstyle.py    (MIT License) View Source Project 5 votes vote down vote up
def sysfilename(filename):
    # type: (Union[str, bytes]) -> bytes
    if not isinstance(filename, text_type):
        return filename
    try:
        return filename.encode(sys.getfilesystemencoding())
    except UnicodeEncodeError:
        try:
            return filename.encode('utf-8')
        except UnicodeEncodeError:
            if HAS_FSCODEC:
                return os.fsencode(filename)
            else:
                raise 
Example 17
Project: bob   Author: BobBuildTool   File: utils.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(self, basePath=None, ignoreDirs=None):
        if basePath:
            self.__index = DirHasher.FileIndex(basePath)
        else:
            self.__index = DirHasher.NullIndex()
        if ignoreDirs:
            self.__ignoreDirs = DirHasher.IGNORE_DIRS | frozenset(os.fsencode(i) for i in ignoreDirs)
        else:
            self.__ignoreDirs = DirHasher.IGNORE_DIRS 
Example 18
Project: bob   Author: BobBuildTool   File: utils.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __hashDir(self, prefix, path=b''):
        entries = []
        try:
            dirEntries = os.listdir(os.path.join(prefix, path if path else b'.'))
        except OSError as e:
            logging.getLogger(__name__).warning("Cannot list directory: %s", str(e))
            dirEntries = []

        for f in dirEntries:
            e = os.path.join(path, f)
            try:
                s = os.lstat(os.path.join(prefix, e))
                if stat.S_ISDIR(s.st_mode):
                    # skip useless directories
                    if f in self.__ignoreDirs: continue
                    # add training '/' for directores for correct sorting
                    f = f + os.fsencode(os.path.sep)
                else:
                    # skip useless files
                    if f in DirHasher.IGNORE_FILES: continue
                entries.append((e, f, s))
            except OSError as err:
                logging.getLogger(__name__).warning("Cannot stat '%s': %s", e, str(err))
        entries = sorted(entries, key=lambda x: x[1])
        dirList = [
            (struct.pack("=L", s.st_mode) + self.__hashEntry(prefix, e, s) + f)
            for (e, f, s) in entries
        ]
        dirBlob = b"".join(dirList)
        m = hashlib.sha1()
        m.update(dirBlob)
        return m.digest() 
Example 19
Project: bob   Author: BobBuildTool   File: utils.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def hashDirectory(self, path):
        self.__index.open()
        try:
            return self.__hashDir(os.fsencode(path))
        finally:
            self.__index.close() 
Example 20
Project: bob   Author: BobBuildTool   File: utils.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def hashPath(self, path):
        path = os.fsencode(path)
        try:
            s = os.lstat(path)
        except OSError as err:
            logging.getLogger(__name__).warning("Cannot stat '%s': %s", path, str(err))
            return b''

        self.__index.open()
        try:
            return self.__hashEntry(path, b'', s)
        finally:
            self.__index.close() 
Example 21
Project: Flask_Blog   Author: sugarguo   File: misc.py    (GNU General Public License v3.0) View Source Project 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 22
Project: Flask_Blog   Author: sugarguo   File: compat.py    (GNU General Public License v3.0) View Source Project 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 23
Project: pip-update-requirements   Author: alanhamlett   File: misc.py    (BSD 2-Clause "Simplified" License) View Source Project 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 24
Project: pip-update-requirements   Author: alanhamlett   File: compat.py    (BSD 2-Clause "Simplified" License) View Source Project 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 25
Project: swjtu-pyscraper   Author: Desgard   File: misc.py    (MIT License) View Source Project 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 26
Project: swjtu-pyscraper   Author: Desgard   File: compat.py    (MIT License) View Source Project 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 27
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: misc.py    (MIT License) View Source Project 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 28
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: compat.py    (MIT License) View Source Project 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 29
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: misc.py    (MIT License) View Source Project 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 30
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: compat.py    (MIT License) View Source Project 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 31
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: misc.py    (MIT License) View Source Project 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 32
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: misc.py    (MIT License) View Source Project 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 33
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: compat.py    (MIT License) View Source Project 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 34
Project: jira_worklog_scanner   Author: pgarneau   File: misc.py    (license) View Source Project 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 35
Project: jira_worklog_scanner   Author: pgarneau   File: compat.py    (license) View Source Project 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 36
Project: zanph   Author: zanph   File: misc.py    (license) View Source Project 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 37
Project: zanph   Author: zanph   File: compat.py    (license) View Source Project 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 38
Project: hostapd-mana   Author: adde88   File: misc.py    (license) View Source Project 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 39
Project: hostapd-mana   Author: adde88   File: compat.py    (license) View Source Project 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 40
Project: hostapd-mana   Author: adde88   File: misc.py    (license) View Source Project 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 41
Project: hostapd-mana   Author: adde88   File: compat.py    (license) View Source Project 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 42
Project: Sci-Finder   Author: snverse   File: misc.py    (license) View Source Project 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 43
Project: Sci-Finder   Author: snverse   File: compat.py    (license) View Source Project 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 44
Project: Sci-Finder   Author: snverse   File: misc.py    (license) View Source Project 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 45
Project: Sci-Finder   Author: snverse   File: compat.py    (license) View Source Project 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 46
Project: ascii-art-py   Author: blinglnav   File: misc.py    (license) View Source Project 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 47
Project: ascii-art-py   Author: blinglnav   File: compat.py    (license) View Source Project 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 48
Project: deb-python-fasteners   Author: openstack   File: _utils.py    (license) View Source Project 5 votes vote down vote up
def _fsencode(path):
        # Replicate similar logic to what py3.2+ fsencode does.
        # See: https://bugs.python.org/issue8514
        encoding = sys.getfilesystemencoding()
        if encoding == 'mbcs':
            errors = 'strict'
        else:
            errors = 'surrogateescape'
        return path.encode(encoding, errors) 
Example 49
Project: deb-python-fasteners   Author: openstack   File: _utils.py    (license) View Source Project 5 votes vote down vote up
def canonicalize_path(path):
    """Canonicalizes a potential path.

    Returns a binary string encoded into filesystem encoding.
    """
    if isinstance(path, six.binary_type):
        return path
    if isinstance(path, six.text_type):
        return _fsencode(path)
    else:
        return canonicalize_path(str(path)) 
Example 50
Project: ivaochdoc   Author: ivaoch   File: misc.py    (license) View Source Project 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__)