Martin Fischer
Martin Fischer

Reputation: 639

How to run a script within a package

I have this project structure:

enter image description here

I am here: 'ls' -> app

I want to run python3 app/tests/NewCoreDeploy.py ...however, it fails ... like this:

Traceback (most recent call last):
    from ..controllers.DigitalOcean import DigitalOcean
ImportError: attempted relative import with no known parent package

I do not understand...every directory contains a __init__.py file ... what am I doing wrong?

Upvotes: 0

Views: 56

Answers (1)

larsks
larsks

Reputation: 311516

When you run python3 app/tests/NewCoreDeploy.py, Python doesn't "know" that the NewCoreDeploy.py file is part of the app package, so relative imports won't work. There are various ways of solving this problem.

Instead of writing:

from ..controllers.DigitalOcean import DigitalOcean

You could write:

from app.controllers.DigitalOcean import DigitalOcean

But then you would need to set PYTHONPATH in order for Python to find the app module, like this (assuming your current directory is the parent of the app directory):

PYTHONPATH=$PWD python3 app/tests/NewCoreDeploy.py

But honestly, just about any time you find yourself setting PYTHONPATH it means you're doing something wrong. In this case, you would probably (a) want to set up your project so that it can be installed (e.g. using pip install), and (b) investigate the use of a testing framework like tox that will take care of installing your projects and dependencies into a virtual environment prior to running tests.

How to set that up is really beyond the scope of this answer, but because so many projects use exactly that setup it's very easy to find examples.

Upvotes: 2

Related Questions