Locate Script Directory
The `locate` library provides simple utilities to find the file location of your current running Python script and manage paths. Currently at version 1.1.1, it receives regular updates, with recent releases adding features like context managers and addressing developer tooling concerns.
Warnings
- breaking The 1.1.1 release notes mention a 'deprecation contract from 4.0.0 to 2.0.0'. While ambiguous, this suggests a revised approach to deprecations, potentially leading to breaking changes or feature removals in future major versions (e.g., 2.0.0). Users should review release notes for versions >= 2.0.0 carefully.
- gotcha When using Pylance in VSCode with `locate` versions prior to 1.1.2, you might encounter a `reportPrivateImportUsage` warning if you import `this_dir` via `import locate` and then use `locate.this_dir`. This was due to `this_dir` not being explicitly listed in `__all__`.
- gotcha The 1.0.0 release introduced `force_relative_location_imports`. Misunderstanding or misusing Python's relative import mechanisms, especially in scripts not run as part of a package or when manipulating `sys.path`, can lead to `ModuleNotFoundError` or unexpected import behavior. This library aims to simplify location, but core Python import rules still apply.
Install
-
pip install locate
Imports
- this_dir
from locate import this_dir
- chdir
from locate import chdir
Quickstart
import os
from locate import this_dir, chdir
# Get the directory of the current script
current_script_dir = this_dir()
print(f"Current script directory: {current_script_dir}")
# Using the chdir context manager
original_cwd = os.getcwd()
print(f"Original CWD: {original_cwd}")
with chdir(current_script_dir):
print(f"CWD inside context: {os.getcwd()}")
# Perform operations relative to current_script_dir
print(f"CWD after context: {os.getcwd()}") # Should revert to original_cwd