MCPcopy Index your code
hub / github.com/python/cpython / expanduser

Function expanduser

Lib/posixpath.py:230–281  ·  view source on GitHub ↗

Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.

(path)

Source from the content-addressed store, hash-verified

228# variable expansion.)
229
230def expanduser(path):
231 """Expand ~ and ~user constructions. If user or $HOME is unknown,
232 do nothing."""
233 path = os.fspath(path)
234 if isinstance(path, bytes):
235 tilde = b'~'
236 else:
237 tilde = '~'
238 if not path.startswith(tilde):
239 return path
240 sep = _get_sep(path)
241 i = path.find(sep, 1)
242 if i < 0:
243 i = len(path)
244 if i == 1:
245 if 'HOME' not in os.environ:
246 try:
247 import pwd
248 except ImportError:
249 # pwd module unavailable, return path unchanged
250 return path
251 try:
252 userhome = pwd.getpwuid(os.getuid()).pw_dir
253 except KeyError:
254 # bpo-10496: if the current user identifier doesn't exist in the
255 # password database, return the path unchanged
256 return path
257 else:
258 userhome = os.environ['HOME']
259 else:
260 try:
261 import pwd
262 except ImportError:
263 # pwd module unavailable, return path unchanged
264 return path
265 name = path[1:i]
266 if isinstance(name, bytes):
267 name = os.fsdecode(name)
268 try:
269 pwent = pwd.getpwnam(name)
270 except KeyError:
271 # bpo-10496: if the user name from the path doesn't exist in the
272 # password database, return the path unchanged
273 return path
274 userhome = pwent.pw_dir
275 # if no user home, return the path unchanged on VxWorks
276 if userhome is None and sys.platform == "vxworks":
277 return path
278 if isinstance(path, bytes):
279 userhome = os.fsencode(userhome)
280 userhome = userhome.rstrip(sep)
281 return (userhome + path[i:]) or sep
282
283
284# Expand paths containing shell variable substitutions.

Callers

nothing calls this directly

Calls 4

_get_sepFunction · 0.85
startswithMethod · 0.45
findMethod · 0.45
rstripMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…