TL;DR
You can solve this by creating a setup.py
file for your project and then running pip install -e .
, instead of modifying sys.path
.
Motivation
This answer might seem to come from left field for this question, but I'm putting it here because OP showed interest in this solution, and I think it's generally a preferable solution to mucking around with sys.path
.
Details
The solution I tend to prefer for my projects is to create an actual setup.py for them, as if I was going to publish them to PyPI, and then run pip install -e .
to have them actually installed in my (possibly virtual) python environment.
Here's a minimalist setup.py
similar to one I used before:
from setuptools import setup
setup(
name="project",
version="0.0.1",
python_requires=">=3.6",
author="Some cool dude",
long_description="Some cool project",
install_requires=["dep1", "dep2"],
)
In another project, I read my requirements.txt
file in my setup.py
:
from setuptools import setup
with open("requirements.txt") as f:
requirements = f.read().splitlines()
setup(
name="project",
version="0.0.1",
python_requires=">=3.6",
author="Some cool dude",
long_description="Some cool project",
install_requires=requirements,
)
With either solution, the setup.py
file is sibling to my project
directory (I use lowercase for my project names, always), both typically being at the root of my Git repo, or under a src
subdirectory.
cd to the directory where setyp.py
and project
are, and run
pip install -e .
and now from anywhere, you can import project
or its submodules and Python will find them.
Suggested reading
Lots more details can be found about setup.py
files at setup.py examples?