userpath
userpath is a cross-platform Python tool designed to simplify the modification of a user's PATH environment variable without requiring elevated privileges. It provides a programmatic and command-line interface to append, prepend, or verify locations within the user's PATH. The library is actively maintained, with its latest version being 1.9.2, and has a consistent release cadence addressing bug fixes and feature enhancements.
Warnings
- breaking Support for Python 2.7 and Python 3.6 was dropped in version 1.8.0. Users running these Python versions must either upgrade their Python environment or use an older version of `userpath` (pre-1.8.0).
- gotcha On non-Windows systems, `userpath`'s behavior regarding which shell configuration files are modified (e.g., only login shells) has fluctuated across recent minor versions (1.9.0 introduced, 1.9.1 temporarily reverted). This could lead to PATH changes not being universally applied across all shell types, requiring users to manually verify or adjust shell configurations.
- gotcha On Windows, while `userpath` attempts to broadcast `WM_SETTINGCHANGE` (since v1.8.0) to notify running applications of PATH updates, many applications, including already open command prompts, PowerShell windows, or IDEs, may not immediately recognize the new `PATH` variable. A full restart of these applications, or even the system, might be necessary.
Install
-
pip install userpath
Imports
- userpath
import userpath
Quickstart
import userpath
import os
# Define a hypothetical directory to add to PATH
location_to_add = os.path.expanduser('~/.local/bin/my_custom_tool')
print(f"Checking if '{location_to_add}' is in current shell's PATH...")
if userpath.in_current_path(location_to_add):
print(f"'{location_to_add}' is already in the current PATH.")
else:
print(f"'{location_to_add}' is NOT in the current PATH.")
print(f"Checking if '{location_to_add}' is in the user's persisted PATH settings...")
if not userpath.in_new_path(location_to_add):
print(f"Appending '{location_to_add}' to user PATH...")
userpath.append(location_to_add)
print(f"'{location_to_add}' has been added to user PATH settings.")
if userpath.need_shell_restart(location_to_add):
print("A new shell or system restart might be required for changes to take full effect.")
else:
print(f"'{location_to_add}' is already configured in the user's PATH settings.")
# To remove a path:
# userpath.remove(location_to_add)