bpo-10496: posixpath.expanduser() catchs pwd.getpwuid() error (GH-10919)
* posixpath.expanduser() now returns the input path unchanged if
the HOME environment variable is not set and pwd.getpwuid() raises
KeyError (the current user identifier doesn't exist in the password
database).
* Add test_no_home_directory() to test_site.
(cherry picked from commit f2f4555d8287ad217a1dba7bbd93103ad4daf3a8)
Co-authored-by: Victor Stinner <vstinner@redhat.com>
diff --git a/Lib/posixpath.py b/Lib/posixpath.py
index e92186c..ca578a5 100644
--- a/Lib/posixpath.py
+++ b/Lib/posixpath.py
@@ -246,7 +246,12 @@
if i == 1:
if 'HOME' not in os.environ:
import pwd
- userhome = pwd.getpwuid(os.getuid()).pw_dir
+ try:
+ userhome = pwd.getpwuid(os.getuid()).pw_dir
+ except KeyError:
+ # bpo-10496: if the current user identifier doesn't exist in the
+ # password database, return the path unchanged
+ return path
else:
userhome = os.environ['HOME']
else:
@@ -257,6 +262,8 @@
try:
pwent = pwd.getpwnam(name)
except KeyError:
+ # bpo-10496: if the user name from the path doesn't exist in the
+ # password database, return the path unchanged
return path
userhome = pwent.pw_dir
if isinstance(path, bytes):