I have a project subdivided into packages, in the following structure:
/project
/pkg
__init__.py
engine.y
ai.py
__init__.py
test_script.py
engine.py has an import statement to use ai.py which looks like
import pkg.ai as ai
This means that test_script.py can be run in the command line as python test_script.py
and it has no issues. However for debugging purposes, engine.py is also often run. When running in PyCharm it has no problems but when using python engine.py
I get errors saying No module named pkg
.
Is there any way I can run engine.py in the command line so that it does not have import errors the way PyCharm does it?
Interestingly the way PyCharm works is that if I do not put that pkg.
in front of the import module, it underlines it in red saying it can't find the module (but still runs). I've looked everywhere for a solution to this but have only got more confused.
The best explanation to this issue was explained here . In short, keep the absolute imports with import pkg.ai
in engine.py but when I want to run the engine module for testing reasons it should be run on the top level (when in project dir) with the module flag, such as:
cd project/
python -m pkg.engine
Make something similar to what you've done with test_script.py
In the same script or in another one in the same level and invoke the scripts from there.
You may also want to read my two answers here and here , they contain two examples on how to use import packages. That should help you understand their usage.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.