diff options
author | Victor Stinner <victor.stinner@haypocalc.com> | 2010-05-08 11:10:09 (GMT) |
---|---|---|
committer | Victor Stinner <victor.stinner@haypocalc.com> | 2010-05-08 11:10:09 (GMT) |
commit | 449c466e7d17292c46c08ef9a458fbdc5ddb7987 (patch) | |
tree | 87f02ca27a0f64708d8618012252d7678f6ac44a /Lib | |
parent | 4cda46ab9167ab6c46e1cbb6caea6fbb021605ac (diff) | |
download | cpython-449c466e7d17292c46c08ef9a458fbdc5ddb7987.zip cpython-449c466e7d17292c46c08ef9a458fbdc5ddb7987.tar.gz cpython-449c466e7d17292c46c08ef9a458fbdc5ddb7987.tar.bz2 |
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.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/os.py | 11 | ||||
-rw-r--r-- | Lib/subprocess.py | 14 |
2 files changed, 14 insertions, 11 deletions
@@ -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() diff --git a/Lib/subprocess.py b/Lib/subprocess.py index 00d36c3..695204a 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -1079,32 +1079,24 @@ class Popen(object): self._set_cloexec_flag(errpipe_write) if _posixsubprocess: - fs_encoding = sys.getfilesystemencoding() - def fs_encode(s): - """Encode s for use in the env, fs or cmdline.""" - if isinstance(s, bytes): - return s - else: - return s.encode(fs_encoding, 'surrogateescape') - # We must avoid complex work that could involve # malloc or free in the child process to avoid # potential deadlocks, thus we do all this here. # and pass it to fork_exec() if env: - env_list = [fs_encode(k) + b'=' + fs_encode(v) + env_list = [os.fsencode(k) + b'=' + os.fsencode(v) for k, v in env.items()] else: env_list = None # Use execv instead of execve. if os.path.dirname(executable): - executable_list = (fs_encode(executable),) + executable_list = (os.fsencode(executable),) else: # This matches the behavior of os._execvpe(). path_list = os.get_exec_path(env) executable_list = (os.path.join(dir, executable) for dir in path_list) - executable_list = tuple(fs_encode(exe) + executable_list = tuple(os.fsencode(exe) for exe in executable_list) self.pid = _posixsubprocess.fork_exec( args, executable_list, |