Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes

for use in the file system, environment variables or the command line.
This commit is contained in:
Victor Stinner 2010-05-08 11:10:09 +00:00
parent 4cda46ab91
commit 449c466e7d
4 changed files with 28 additions and 11 deletions

View file

@ -504,6 +504,17 @@ if name not in ('os2', 'nt'):
return environb.get(key, default)
__all__.append("getenvb")
if name != 'nt':
def fsencode(value):
"""Encode value for use in the file system, environment variables
or the command line."""
if isinstance(value, bytes):
return value
elif isinstance(value, str):
return value.encode(sys.getfilesystemencoding(), 'surrogateescape')
else:
raise TypeError("expect bytes or str, not %s" % type(value).__name__)
def _exists(name):
return name in globals()