Python os 模块,fsencode() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.fsencode()

项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)},
                      ])
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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__)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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__)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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.
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def gettempprefixb():
    """The default prefix for temporary directories as bytes."""
    return _os.fsencode(gettempprefix())
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def gettempdirb():
    """A bytes version of tempfile.gettempdir()."""
    return _os.fsencode(gettempdir())
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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")
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
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__)
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
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__)
项目:whatstyle    作者:mikr    | 项目源码 | 文件源码
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
项目:whatstyle    作者:mikr    | 项目源码 | 文件源码
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
项目:whatstyle    作者:mikr    | 项目源码 | 文件源码
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
项目:bob    作者:BobBuildTool    | 项目源码 | 文件源码
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
项目:bob    作者:BobBuildTool    | 项目源码 | 文件源码
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()
项目:bob    作者:BobBuildTool    | 项目源码 | 文件源码
def hashDirectory(self, path):
        self.__index.open()
        try:
            return self.__hashDir(os.fsencode(path))
        finally:
            self.__index.close()
项目:bob    作者:BobBuildTool    | 项目源码 | 文件源码
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()
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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__)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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__)
项目:pip-update-requirements    作者:alanhamlett    | 项目源码 | 文件源码
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__)
项目:pip-update-requirements    作者:alanhamlett    | 项目源码 | 文件源码
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__)
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
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__)
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
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__)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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__)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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__)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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__)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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__)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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__)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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__)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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__)
项目:jira_worklog_scanner    作者:pgarneau    | 项目源码 | 文件源码
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__)
项目:jira_worklog_scanner    作者:pgarneau    | 项目源码 | 文件源码
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__)
项目:zanph    作者:zanph    | 项目源码 | 文件源码
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__)
项目:zanph    作者:zanph    | 项目源码 | 文件源码
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__)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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__)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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__)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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__)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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__)
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
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__)
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
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__)
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
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__)
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
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__)
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
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__)
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
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__)
项目:deb-python-fasteners    作者:openstack    | 项目源码 | 文件源码
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)
项目:deb-python-fasteners    作者:openstack    | 项目源码 | 文件源码
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))
项目:ivaochdoc    作者:ivaoch    | 项目源码 | 文件源码
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__)