Reputation: 1753
I have a project that relies heavily on database credentials, and it is convenient to put them in one location, but I have numerous subfolders that need to import
that file. From a lot of searching, it seems like there are many (suboptimal/overly complicated) ways to do this, but I'm wondering what is the simplest way to include one file across many directories.
project/
credentials.py
task1/
fileA.py
task2/
fileB.py
where credentials.py
looks like this:
database = "my_database"
database_user = "me"
database_password = "password"
What's the best way to import
the contents of credentials.py
in fileA.py
and fileB.py
? Is there a completely different and better way to structure this project?
EDIT: Is there a way to accomplish this so that it does not matter which directory I run each task from?
Upvotes: 3
Views: 185
Reputation: 1199
You could just add export PYTHONPATH=$PYTHONPATH:/path/to/directory/with/credentials
to your ~/.bashrc
, reopen your shell and then just use import credentials
.
This is assuming your on a UNIX based system.
For windows the docs says you can add set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
to your autoexec.bat
file. msconfig
is a graphical interface to this file.
Upvotes: 1
Reputation: 1840
I just happened to have the same issue today. You can insert the following in fileA.py and fileB.py:
import sys, os
# prepend parent directory to path
sys.path = [os.path.join(os.path.dirname(__file__), os.pardir)] + sys.path
import credentials
Upvotes: 2