Forums

How do I set the PYTHONPATH for a module to be imported in interactive mode?

I can make things work but what I need to be able to do is to show students how to use the PYTHONPATH to allow a custom module to be imported. I tried to set it up in the pythonstartup.py file but not getting it right.

I can import fine if open BASH in that directory. It also works if I place a copy of the file in site-packages.

To be able to complete my lesson I still would like to be able to show students how to properly set the PYTHONPATH variable in PythonAnywhere. Help!

You can do a

import sys
sys.path.append('/path/to/folder')

You can also change your working directory so that '.' is referring to the correct location

import os
os.chdir('/path/to/folder')

Thanks Conrad,

Adding to the system path is not a problem. Just looking to set the PYTHONPATH so that modules can be found in a non-standard directory.

This is what I came up with. I can set the PYTHONPATH in the .bashrc file and it will be set for the Bash console. And the PYTHONPATH will be inherited by the Python process executed from the Bash command line but the import function still doesn't find the module.

The PYTHONPATH can be set for Python interactive mode, a Python console, by setting it in the .pythonstartup.py file. But still can't import a module.

What does work is to click 'Open Bash console here' when in the directory that the module resides in (under the Files tab). And starting Python from the command line.

Easier way to get it to work is to place the module in the site-packages directory. For me that is in /home/DanCarroll/.local/lib/python3.5/site-packages.

Another option that works while leaving the module in a sub-directory other than site-packages is to make use of the init.py file. Place empty copies of init.py in each directory leading to your module from your home directory.

Here is what worked for me and my directory/file layout.

/home/DanCarroll

.
| - - PythonCourse
|  | - - __init__.py
|  | - - Chapter9
|  | - - __init__.py
|  | - - MyLibrary.py

To import the module from the Python shell, type

>>> from PythonCourse.Chapter9.MyLibrary import *

Just to clarify, you are asking about how to import your module without having to add to the sys.path etc each time right?

And you are having trouble now because say the student is working on /home/<username>/folder1/script1.py, and so their working directory is /home/<username>/folder1 if they run the python script from our editor, and so isn't able to import from /home/<username>/PythonCourse?

And it turns out that the init.py files aren't even needed.

So to import code from a module that is not in the current active directory or in the site-packages folder (directory) use the 'from library import module' statement.

Example: from directory.sub-directory.MyLibrary import my_function

Yes Conrad, that is basically what I am attempting.

Hi just wonder if this advice from conrad worked.