Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...