我正在Windows上的Wing IDE中运行PyLint.我的项目中有一个子目录(包),在包中我从顶层导入一个模块,即.
__init__.py
myapp.py
one.py
subdir\
__init__.py
two.py
Run Code Online (Sandbox Code Playgroud)
在two.py我内部import one,这在运行时工作正常,因为顶级目录(从中myapp.py运行)位于Python路径中.但是,当我在two.py上运行PyLint时,它给出了一个错误:
F0401: Unable to import 'one'
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
背景
我有一个Python应用程序,它依赖于另一个作为git子模块提供的包,产生类似于以下内容的目录结构:
foo/
bar/
bar/
__init__.py
eggs.py
test/
setup.py
foo/
__init__.py
ham.py
main.py
Run Code Online (Sandbox Code Playgroud)
从顶层目录执行该访问foo包就足够简单了。但是该程序包嵌套在另一个目录中,不能直接导入。main.pyfoo/barbar
通过sys.path在以下内容的开头进行修改,可以轻松解决此问题main.py:
import sys
# Or sys.path.append()
sys.path.insert(0, './bar')
from bar.eggs import Eggs
from foo.ham import Ham
Run Code Online (Sandbox Code Playgroud)
(注意:此代码示例假定main.py将始终从中调用foo/;如果情况并非如此,则'.bar'可以将其替换,os.path.join(os.path.dirname(__file__), 'bar')尽管这样做显然比较麻烦。)
问题
不幸的是,pylint不喜欢这种解决方案。当代码工作时,lint认为sys.path修改是结束于“模块顶部”的代码块,并给出了不希望的wrong-import-position警告:
C: 6, 0: Import "from bar.eggs import Eggs" should be placed at the top of the module (wrong-import-position)
C: 7, 0: Import "from foo.ham …Run Code Online (Sandbox Code Playgroud)