简体   繁体   English

Pycharm 中的相对导入

[英]Relative imports in Pycharm

Some authoritative names have commented and/or answered about the general problem of relative imports when trying to run a script within the module directory here: Relative imports in Python 3当尝试在模块目录中运行脚本时,一些权威名称评论和/或回答了relative imports的一般问题: Python 3 中的相对导入

My issue is that the Pycharm IDE is parsing the module and running it in this same directory.我的问题是Pycharm IDE正在解析模块并在同一目录中运行它。 So I end up with import errors.所以我最终遇到了导入错误。 Note that there is an __init__.py in the package.请注意,包中有一个__init__.py Looks fine to pycharm parser pycharm解析器看起来不错

在此处输入图片说明

from . logger import *   # Logger is a module in same package

But ..但是..

在此处输入图片说明

Traceback (most recent call last):
  File "/git/bluej/fusion/python/pointr/bluej/util/DB.py", line 6, in <module>
    from . logger import *
ImportError: attempted relative import with no known parent package

the Run Configuration was created by right-clicking in the module. Run Configuration是通过在模块中右键单击创建的。 The auto generated version is like this: having the working directory the same as the script dir.自动生成的版本是这样的: working directory与脚本目录相同。 /git/bluej/fusion/python/pointr/bluej/util (note the package is pointr.blue.util ): /git/bluej/fusion/python/pointr/bluej/util (注意包是pointr.blue.util ):

在此处输入图片说明

I tried out putting the Working Directory at the base python directory level: /git/bluej/fusion/python/我尝试将Working Directory放在基本python目录级别: /git/bluej/fusion/python/

在此处输入图片说明

However that did not have any effect.然而这并没有任何影响。

Responding to a comment: logger is not the root package and so the following code does not work:回应评论: logger不是根包,因此以下代码不起作用:

在此处输入图片说明

How can I develop, debug, and run modules with relative imports in Pycharm ?如何在Pycharm开发、调试和运行具有相对导入的Pycharm

在此处输入图片说明

  • Change script name to module name : see the first selection under Configuration将脚本名称更改为模块名称:请参阅Configuration下的第一个选择
  • Change working directory to root of the hierarchy将工作目录更改为层次结构的根目录
  • hope for the best希望最好的

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

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