In Bash, to get a fully-qualified path with any environment variables substituted from the environment, I can use the realpath command. How can I do this in Python?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In Python, replicating realpath's functionality (including environment variable substitution, absolute path conversion, normalization, and symlink resolution) involves a combination of functions from the os.path module or the pathlib module.
The key steps are:
Expand environment variables: Resolve $VAR and ${VAR}.
Expand user home directory: Resolve ~ and ~user.
Resolve to a real, absolute path: Convert relative paths, normalize . and .., and resolve symbolic links.
Let's look at the best ways to do this.
Method 1: Using os.path (The "Classic" Way)
This method uses functions from the os.path module, which are well-established and widely used.
python
import os
def get_real_path_os_path(path_string: str) -> str:
"""
Gets a fully-qualified path, expanding environment variables and user home,
and resolving to the real path (including symlinks).
"""
# 1. Expand environment variables ($VAR, ${VAR})
expanded_path = os.path.expandvars(path_string)
# 2. Expand user home directory (~, ~user)
expanded_path = os.path.expanduser(expanded_path)
# 3. Resolve to the real, absolute path (normalize, resolve symlinks)
# strict=True (default): Raises FileNotFoundError if path doesn't exist.
# strict=False: Resolves as much as possible, leaves non-existent parts.
# We generally want strict=True to match realpath's strictness, but for
# cases where you just want to see the "intended" path, False might be useful.
try:
real_path = os.path.realpath(expanded_path)
except FileNotFoundError:
# If the path doesn't exist, realpath (with strict=True) will fail.
# You might want to fall back to abspath in this case, or re-raise,
# depending on your desired behavior.
# For a strict match to realpath, re-raise or let it fail.
# If you want it to just return what it *would* be if it existed:
real_path = os.path.abspath(expanded_path)
print(f"Warning: Path '{path_string}' (resolved to '{expanded_path}') does not fully exist. "
f"Returning absolute path instead of realpath.")
return real_path
# --- Examples ---
print(f"Current Working Directory: {os.getcwd()}")
print("-" * 30)
# Example 1: Basic relative path
path1 = "test_data/./../another_dir/file.txt"
# Create dummy files for demonstration
os.makedirs("test_data", exist_ok=True)
os.makedirs("another_dir", exist_ok=True)
with open("another_dir/file.txt", "w") as f:
f.write("hello")
print(f"Input: '{path1}'")
print(f"Output: '{get_real_path_os_path(path1)}'\n") # Expected: .../another_dir/file.txt
# Example 2: User home directory
path2 = "~/Documents/my_doc.pdf" # Assuming Documents exists in home
os.makedirs(os.path.expanduser("~/Documents"), exist_ok=True)
with open(os.path.expanduser("~/Documents/my_doc.pdf"), "w") as f:
f.write("doc content")
print(f"Input: '{path2}'")
print(f"Output: '{get_real_path_os_path(path2)}'\n") # Expected: /home/user/Documents/my_doc.pdf
# Example 3: Environment variable
# Set an environment variable for testing
os.environ['MY_PROJECT_ROOT'] = os.path.abspath(os.path.join(os.getcwd(), "project_root"))
os.makedirs(os.environ['MY_PROJECT_ROOT'], exist_ok=True)
with open(os.path.join(os.environ['MY_PROJECT_ROOT'], "config.ini"), "w") as f:
f.write("config")
path3 = "$MY_PROJECT_ROOT/config.ini"
print(f"Input: '{path3}' (MY_PROJECT_ROOT={os.environ['MY_PROJECT_ROOT']})")
print(f"Output: '{get_real_path_os_path(path3)}'\n") # Expected: .../current_dir/project_root/config.ini
# Example 4: Path with symlink
symlink_target = os.path.join(os.getcwd(), "target_file.txt")
symlink_path = os.path.join(os.getcwd(), "link_to_file.txt")
with open(symlink_target, "w") as f:
f.write("target")
if os.path.exists(symlink_path):
os.remove(symlink_path)
os.symlink(symlink_target, symlink_path)
print(f"Input: '{symlink_path}' (symlink to '{symlink_target}')")
print(f"Output: '{get_real_path_os_path(symlink_path)}'\n") # Expected: .../current_dir/target_file.txt
# Example 5: Non-existent path (strict=True behavior)
path5 = "/non/existent/path/file.txt"
print(f"Input: '{path5}' (non-existent)")
print(f"Output: '{get_real_path_os_path(path5)}'\n") # Will print warning and return abspath
# Clean up dummy files/dirs
import shutil
shutil.rmtree("test_data", ignore_errors=True)
shutil.rmtree("another_dir", ignore_errors=True)
shutil.rmtree(os.path.expanduser("~/Documents"), ignore_errors=True)
shutil.rmtree(os.environ['MY_PROJECT_ROOT'], ignore_errors=True)
if os.path.exists(symlink_target): os.remove(symlink_target)
if os.path.exists(symlink_path): os.remove(symlink_path)
del os.environ['MY_PROJECT_ROOT']
Explanation of steps:
os.path.expandvars(path): Replaces $name or ${name} in the string with the value of the environment variable name. Missing variables are left unchanged.
os.path.expanduser(path): Replaces ~ with the user's home directory (os.path.expanduser('~')) and ~user with that user's home directory. This should be done afterexpandvars if you expect environment variables to resolve to a path that starts with ~ (though this is less common).
os.path.realpath(path): This is the equivalent of realpath in Bash.
It calls os.path.abspath() first to convert the path to an absolute path.
It then resolves any . and .. components.
Crucially, it resolves all symbolic links in the path.
Important: By default (strict=True), os.path.realpath() will raise a FileNotFoundError if any component of the path does not exist or if a symlink loop is detected. If you want it to resolve as much as possible even for non-existent paths, you can use strict=False, which behaves more like os.path.abspath for non-existent parts. The Bash realpath command does require components to exist for full resolution.
Method 2: Using pathlib (The "Modern" Way)
The pathlib module provides an object-oriented approach to filesystem paths, which is often more readable and convenient.
python
Explanation of steps:
Path(path_string).expanduser(): This directly expands ~ and ~user at the beginning of the path string.
os.path.expandvars(str(p)): pathlib's Path objects don't have a direct expandvars() method. You need to convert the Path object to a string (str(p)), expand the variables using os.path.expandvars(), and then convert it back into a Path object.
p.resolve(): This is the pathlib equivalent of os.path.realpath(). It resolves all symbolic links, . and .. components, and returns the absolute, canonical path. Like os.path.realpath(), it also accepts a strict argument (default True) and will raise FileNotFoundError if components don't exist.
Which method to choose?
os.path: If you are dealing primarily with string paths and don't need the object-oriented features of pathlib, this is perfectly fine. It's often preferred for legacy codebases or when interoperating directly with functions that expect string paths.
pathlib: Generally recommended for new Python code. It offers a more modern, object-oriented, and often more readable way to handle paths. It makes operations like joining paths, checking file types, and iterating directories much cleaner. The slight inconvenience of needing os.path.expandvars for variable expansion is usually outweighed by its other benefits.
Both methods provide the full functionality of realpath including environment variable substitution. Remember the strict argument for realpath/resolve if you need to control behavior for non-existent paths.
from pathlib import Path
import os
def get_real_path_pathlib(path_string: str) -> Path:
"""
Gets a fully-qualified path using pathlib, expanding environment variables
and user home, and resolving to the real path (including symlinks).
Returns a Path object.
"""
# Create a Path object from the string
p = Path(path_string)
# 1. Expand user home directory (~, ~user)
# Path.expanduser() automatically handles this.
p = p.expanduser()
# 2. Expand environment variables ($VAR, ${VAR})
# Pathlib doesn't have a direct equivalent to os.path.expandvars()
# that returns a Path object, so we convert to string, expand, then back to Path.
p = Path(os.path.expandvars(str(p)))
# 3. Resolve to the real, absolute path (normalize, resolve symlinks)
# strict=True (default): Raises FileNotFoundError if path doesn't exist.
# strict=False: Resolves as much as possible, leaves non-existent parts.
try:
resolved_path = p.resolve()
except FileNotFoundError:
print(f"Warning: Path '{path_string}' (resolved to '{p}') does not fully exist. "
f"Returning absolute path instead of realpath.")
resolved_path = p.absolute() # Fallback to absolute if not found
return resolved_path
# --- Examples (same as above for comparison) ---
print(f"Current Working Directory: {os.getcwd()}")
print("-" * 30)
# Create dummy files for demonstration (re-run if you cleaned up from prev example)
os.makedirs("test_data", exist_ok=True)
os.makedirs("another_dir", exist_ok=True)
with open("another_dir/file.txt", "w") as f: f.write("hello")
os.makedirs(os.path.expanduser("~/Documents"), exist_ok=True)
with open(os.path.expanduser("~/Documents/my_doc.pdf"), "w") as f: f.write("doc content")
os.environ['MY_PROJECT_ROOT'] = os.path.abspath(os.path.join(os.getcwd(), "project_root"))
os.makedirs(os.environ['MY_PROJECT_ROOT'], exist_ok=True)
with open(os.path.join(os.environ['MY_PROJECT_ROOT'], "config.ini"), "w") as f: f.write("config")
symlink_target = os.path.join(os.getcwd(), "target_file.txt")
symlink_path = os.path.join(os.getcwd(), "link_to_file.txt")
with open(symlink_target, "w") as f: f.write("target")
if os.path.exists(symlink_path): os.remove(symlink_path)
os.symlink(symlink_target, symlink_path)
path1 = "test_data/./../another_dir/file.txt"
print(f"Input: '{path1}'")
print(f"Output: '{get_real_path_pathlib(path1)}'\n")
path2 = "~/Documents/my_doc.pdf"
print(f"Input: '{path2}'")
print(f"Output: '{get_real_path_pathlib(path2)}'\n")
path3 = "$MY_PROJECT_ROOT/config.ini"
print(f"Input: '{path3}' (MY_PROJECT_ROOT={os.environ['MY_PROJECT_ROOT']})")
print(f"Output: '{get_real_path_pathlib(path3)}'\n")
symlink_path = os.path.join(os.getcwd(), "link_to_file.txt")
print(f"Input: '{symlink_path}'")
print(f"Output: '{get_real_path_pathlib(symlink_path)}'\n")
path5 = "/non/existent/path/file.txt"
print(f"Input: '{path5}' (non-existent)")
print(f"Output: '{get_real_path_pathlib(path5)}'\n")
# Clean up (same as before)
import shutil
shutil.rmtree("test_data", ignore_errors=True)
shutil.rmtree("another_dir", ignore_errors=True)
shutil.rmtree(os.path.expanduser("~/Documents"), ignore_errors=True)
shutil.rmtree(os.environ['MY_PROJECT_ROOT'], ignore_errors=True)
if os.path.exists(symlink_target): os.remove(symlink_target)
if os.path.exists(symlink_path): os.remove(symlink_path)
del os.environ['MY_PROJECT_ROOT']