Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PyCharm handle relative imports of modules?

I have the following directory structure on a project that has been inherited:

work_dir/
    FlaskControlPanel/
        static/
        templates/
        app.py
    models/
        __init__.py
        model1.py
        model2.py
    script1.py
    script2.py

From script1.py or script2.py I can run this from models.model1 import Class1, Class2 and it works. When using PyCharm, I can use the same import line within app.py.

However, when I go to deploy this on my dev server, this doesn't work from app.py. I get the error ImportError: No module named models.model1

What does PyCharm do to get around this?

How can I fix my import in app.py to work in both PyCharm and when I run my Flask application on the development server? I usually run it on the server just using python app.py from within the FlaskControlPanel directory.

like image 358
NewGuy Avatar asked May 23 '14 13:05

NewGuy


1 Answers

You have to make sure work_dir is added in to sys.path or PYTHONPATH.

Python will add the parent folder of the script file into sys.path automatically. So if you run app.py in your shell, only FlaskControlPanel will be inserted into sys.path and python cannot find where models is (work_dir is not in sys.path).

But in pycharm, it will always add work_dir in sys.path. That's why you can run app.py without any problem.

For your problem, you can change directory to work_dir and run PYTHONPATH=. python FlaskControlPanel/app.py

https://docs.python.org/2/using/cmdline.html#interface-options

Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to either a Python file, a directory containing a __main__.py file, or a zipfile containing a __main__.py file.

If this option is given, the first element of sys.argv will be the script name as given on the command line.

If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.

If the script name refers to a directory or zipfile, the script name is added to the start of sys.path and the __main__.py file in that location is executed as the __main__ module.

like image 145
hoozecn Avatar answered Oct 18 '22 01:10

hoozecn