aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Lib/getpass.py
diff options
context:
space:
mode:
authorJacob Walls <jacobtylerwalls@gmail.com>2023-11-27 13:05:55 -0500
committerGitHub <noreply@github.com>2023-11-27 10:05:55 -0800
commit99a73c3465a45fe57cac01a917fc50e0743b5964 (patch)
treebe3c8979398f0e81a6e9d5bccb7b3d715f1cb418 /Lib/getpass.py
parent936c503a442ee062c837e334f237796554c792ff (diff)
downloadcpython-99a73c3465a45fe57cac01a917fc50e0743b5964.tar.gz
cpython-99a73c3465a45fe57cac01a917fc50e0743b5964.zip
gh-76912: Raise OSError from any failure in getpass.getuser() (#29739)
* bpo-32731: Raise OSError from any failure in getpass.getuser() Previously, if the username was not set in certain environment variables, ImportError escaped on Windows systems, and it was possible for KeyError to escape on other systems if getpwuid() failed.
Diffstat (limited to 'Lib/getpass.py')
-rw-r--r--Lib/getpass.py13
1 files changed, 10 insertions, 3 deletions
diff --git a/Lib/getpass.py b/Lib/getpass.py
index 8b42c0a536b..bd0097ced94 100644
--- a/Lib/getpass.py
+++ b/Lib/getpass.py
@@ -156,7 +156,11 @@ def getuser():
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
+ Any failure to find a username raises OSError.
+ .. versionchanged:: 3.13
+ Previously, various exceptions beyond just :exc:`OSError`
+ were raised.
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
@@ -164,9 +168,12 @@ def getuser():
if user:
return user
- # If this fails, the exception will "explain" why
- import pwd
- return pwd.getpwuid(os.getuid())[0]
+ try:
+ import pwd
+ return pwd.getpwuid(os.getuid())[0]
+ except (ImportError, KeyError) as e:
+ raise OSError('No username set in the environment') from e
+
# Bind the name getpass to the appropriate function
try: