Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling common files in Python

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?

like image 753
jczaplew Avatar asked Nov 28 '25 12:11

jczaplew


2 Answers

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
like image 116
Wes Avatar answered Nov 30 '25 03:11

Wes


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.

like image 45
Daniel Timberlake Avatar answered Nov 30 '25 01:11

Daniel Timberlake