首页 > 解决方案 > ImportError using python if __name__ == "__main__"

问题描述

I currently inherited a codebase that looks something like this.

project
manage.py
   |_ config
           |_ settings
           |_ wsgi.py
   |_ project
            |_ app1
            |_ app2
            |.... <-- many more Django apps
            |_ a_new_app
                 |_ __init__.py                  
                 |_ run.py
                 |_ foo.py
                 |_ bar.py

I added a new app with some .py files which imports from other apps too in the same package and other app packages too in the project. All is well till I tried to run

python project/a_new_app/run.py

Then I started getting import error here is how my run.py looks.

# run.py
from project.a_new_app.foo import Foo

class App():
    def method(self, key):
        data = {"some-key": Foo}
        return data.get(key)

    .... more methods here

if __name__ == "__main__":

    app = App()
    app.loop_forever()

I got this error

File "project/a_new_app/run.py", line 7, in <module>
    from project.a_new_app.foo import Foo
ImportError: No module named project.a_new_app.foo

My working directory is /user/me/PycharmProjects/project, Thanks.

标签: djangopython-2.7

解决方案


from project.a_new_app.foo import Foo

For this import to work, you need the outer project directory (the one containing manage.py and the inner project directory) to be on the Python path.

However, run.py is two directories deeper than that, in project/a_new_app. Therefore you need to add ../.. to the python path at the top of the module.

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

from project.a_new_app.foo import Foo
...

推荐阅读