Henri
Henri

Reputation: 205

Import python files from other directory without sys.path.append or changing PATH

I have the following folder structure

project
  +folder src
    +file main.py
    +file __init__.py
  +folder tests
    +file test.py
    +file __init__.py
  +file __init__.py

All __init__ files are empty.

Now I want to be able to run test.py form anywhere, this is important.

test.py calls

import src

because it needs functions from main.py. This leads to an error:

ImportError: no module named src

Solutions I found include adding a sys.path.append command to test.py or adding the folder src to my PATH environment variable - is there no other way?

I cannot force every user to change their PATH and I cannot add sys.path.append commands to all test files.

Upvotes: 2

Views: 1508

Answers (1)

Justin Fay
Justin Fay

Reputation: 2606

You can create a package of your application and install it in the environment you are running the tests from. See here for a tutorial http://python-packaging.readthedocs.org/en/latest/

Upvotes: 1

Related Questions