我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.fsencode()。
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)
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)
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)}, ])
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)
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)
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__)
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__)
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.
def gettempprefixb(): """The default prefix for temporary directories as bytes.""" return _os.fsencode(gettempprefix())
def gettempdirb(): """A bytes version of tempfile.gettempdir().""" return _os.fsencode(gettempdir())
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")
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
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
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
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
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()
def hashDirectory(self, path): self.__index.open() try: return self.__hashDir(os.fsencode(path)) finally: self.__index.close()
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()
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)
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))