【问题标题】:Adding a path to sys.path in python and pylint在 python 和 pylint 中添加 sys.path 的路径
【发布时间】:2017-11-27 16:56:25
【问题描述】:

所以。我知道这个问题似乎已经被问死了,但似乎没有一个答案能解决想要做什么。

我在另一个目录中有一个库,我想将它包含在我运行的一组 other 项目中。我不希望每次运行 python 时都添加那个库

所以,我 一直在我的 python 代码中这样做:

import sys
sys.path.append("/tmp/demo/src/my-lib")
import MyClass

这很好用。但是,现在我发现并喜欢 pylint,它抱怨说

E:  7, 0: Unable to import 'MyClass' (import-error)
C:  7, 0: Import "import MyClass" should be placed at the top of the module (wrong-import-position)

我知道我可以使用指令禁用 import-error 和 wrong-import-position(或者只是将其放入 .pylintrc ...)但是,我宁愿不这样做。我想知道将路径添加到 sys.path 的“正确”方式,该路径不是 global 我的项目,只是添加到使用它的项目子集特定的图书馆。

这可能吗?

【问题讨论】:

    标签: python pylint


    【解决方案1】:

    您可以使用 pylint 的“初始化钩子”来完成。看到这个答案:https://stackoverflow.com/a/3065082/4323

    还有this statement from pylint's bug tracker

    我们可能不会自动支持此功能。但是现在我们确实支持手动添加路径,虽然方式更麻烦,通过 ``--init-hook="import sys; sys.path.append(...)"

    【讨论】:

      【解决方案2】:

      这是一篇旧帖子,但在搜索了一段时间后,我无法真正找到解决问题的简单方法,因此也许这种解决方法对其他人也有用。最近我在 Visual Studio Code 中使用 python linter 时遇到了类似的问题:每次我在 VSC 中保存我的 python 文件时,linter 都会将 sys.import 放在导入代码后面,因此我的模块无法加载。

      我知道这可以通过更改 PYTHONPATH 等和更改 linter 配置文件来解决,但在我的情况下,我无法更改所有这些,因为该模块是另一个应用程序的一部分。

      作为一种解决方法,我通过以下方式解决了 lint 错误:

      import sys
      
      if 1==1:
          sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
          import mylib
      

      这阻止了 linter 抱怨和 VSC 格式化程序重新安排我的导入规则。

      【讨论】:

        猜你喜欢
        • 2015-10-03
        • 2023-03-23
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        • 2018-11-24
        • 1970-01-01
        相关资源
        最近更新 更多