I have a project called library and in it I have 3 folders - user, book and main. There is a user_utility.py in user. So let's say the project folder is:
/User/me/Projects/library/user/user_utility.py
/User/me/Projects/library/book/book_utility.py
/User/me/Projects/library/main/main.py
Now, in /User/me/Projects/library/main/main.py I would like to write the import statement as:
from user.user_utility import UserUtility
What is the $PYTHONPATH variable that allows me to do so? I tried
EXPORT PYTHONPATH="/User/me/Projects/library
but it does not work and it threw
No module named user.user_utility
2 Answers 2
Messing with PYTHONPATH really is the wrong approach to go forward here. Instead, turn your user and book folders into proper modules/submodules. For doing so, you need to add __init__.py -files to (both of) them, looking like this for example:
from user_utility import some_routine
In your example, this would be /User/me/Projects/library/user/__init__.py. Now you can import this routine from your main.py-file as follows:
from user import some_routine
For full reference, have a look at the python documentation, modules tutorial.
1 Comment
If you call main.py directly from the command line, you can set the environment variable at the beginning of the line:
PYTHONPATH=/User/me/Projects/Library python main.py
Otherwise, you should be able to set that module lookup path with:
export PYTHONPATH=/User/me/Projects/Library
To verify, you can see your environment variables with:
env
Also, make sure to put the __init__.py inside the user folder.
__init__.py.