0

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?

2
  • Is your question about how to add the above path in the environment variables (PATH) programmatically? or would it be okay to do command line (or other methods) Commented Jun 25, 2015 at 9:34
  • @AnandSKumar I would like to know both ways if its possible. also I was thinking if there's a way to know to make that happen through __init__.py Commented Jun 25, 2015 at 9:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.