简体   繁体   English

Python / PyCharm:运行子包模块时的差异

[英]Python/PyCharm: Differences when running subpackage modules

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 engine.py具有使用ai.py的import语句,如下所示

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. 这意味着test_script.py可以像python test_script.py一样在命令行中运行,并且没有问题。 However for debugging purposes, engine.py is also often run. 但是,出于调试目的,通常也会运行engine.py。 When running in PyCharm it has no problems but when using python engine.py I get errors saying No module named pkg . 在PyCharm中运行时没有问题,但是在使用python engine.py时出现错误,提示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? 有什么办法可以在命令行中运行engine.py,使其不像PyCharm那样出现导入错误?

Interestingly the way PyCharm works is that if I do not put that pkg. 有趣的是,PyCharm的工作方式是如果我不输入该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: 简而言之,将绝对导入保留为import pkg.ai在engine.py中,但是当出于测试原因而要运行引擎模块时,应使用模块标志在顶层(在项目目录中)运行,例如:

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. 用与test_script.py类似的方法在同一脚本中或在同一级别的另一个脚本中进行操作,然后从那里调用脚本。

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. 那应该可以帮助您了解它们的用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM