Reading Python Module from different PATH

116 views Asked by At

I have a directory layout like this:

Pytest\
  __init__.py
  connect.py
  sql.py
  test.py

what I want to do is that Pytest directory would be in my python environment path so that I can import all the modules i.e. connect.py, sql.py or test.py anywhere outside this directory or even the interactive shell.

This is what I have in my __init__.py:

from .connect import *
from .sql import *
from .test import *

for this I think I the parent directory should be in python path. The question is how should I go about it?

1

There are 1 answers

0
Anand S Kumar On BEST ANSWER

For setting the Python path from inside a python script, you can use the sys.path.append() method, this method takes the directory as string which you need to add to the python path.

Example -

import sys
sys.path.append(dir)

Where dir is the directory you want to add to the path , after this any files within the dir file can be imported without issues.

To set the python to take python files from a different directory directly through the terminal or other means, you need to set the PYTHONPATH variable, and not the PATH variable (PATH variable is used by the system to find executables, its not used by Python to find modules/python files) .

PYTHONPATH - This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.