python-3.x - 如何在 VS Code 中正确导入 Python 模块?

标签 python-3.x visual-studio-code pylint

我最近开始用 Python 编程,我决定用 Python 编写一些 Delphi 函数。我决定创建一个单独的 Python 模块来保存我的函数。

现在,我尝试导入它,但在 Visual Studio Code 中出现此错误:

unable to import 'functions' pylint(import error) [5, 1]

这是我的代码:

import sys

sys.path.append('/Users/user123/Desktop/Python/Functions/')

import functions

这是一张图片:

/image/5EGbk.jpg

最佳答案

鉴于您的文件/文件夹结构:

├── Functions
│   └── functions.py
├── <main app folder>
│   └── app.py
尽管添加 path/to/Functions 后您的导入可能会正确运行至sys.path , Pylint 会向您发出警告,因为这不是推荐的声明导入方式,尤其是当您在应用程序包/文件夹之外导入模块时。
来自 PEP8 Style Guide for Imports :

Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path):

import mypkg.sibling 
from mypkg import sibling 
from mypkg.sibling import example

推荐的解决方案是 setup Functions as a package通过添加 __init__.py在它下面的文件:
├── parent
│   └── Functions
│       ├── __init__.py
│       └── functions.py
然后导入您的函数,如以下之一:
sys.path.append("/path/to/parent")

# option 1
from Functions import functions
functions.copy()
functions.delete()

# option2
from Functions.functions import copy, delete
copy()
delete()
这两个选项都应该正确运行并满足 PyLint。
现在,如果你真的想做一个非绝对的导入,比如 from functions import func ,并让 PyLint 接受,我建议重命名 functions.py到别的东西。这是因为,在某些不区分大小写的系统上,导入 Functionsfunctions可以被视为相同的模块。当你告诉 PyLint 查看 /path/to/Functions (我稍后会展示),它可能无法区分 copydeleteFunctions 的一部分或 functions ,它可能仍会显示导入错误。
所以,你需要做的是重命名 functions.py (例如 filefuncs.py ):
├── Functions
│   └── filefuncs.py
├── <main app folder>
│   └── app.py
然后在您的 VS Code 工作区中,将其添加到您的 .vscode/settings.json 文件中,以告诉 PyLint 在哪里寻找 filefuncs模块:
"python.linting.pylintArgs": [
    "--init-hook",
    "import sys; sys.path.append('/path/to/Functions')"
]
然后,您现在可以像原始代码一样导入它,但不会出现 PyLint 错误:
sys.path.append("/path/to/Functions")
from filefuncs import copy, delete
copy()
delete()
第二种方法将为您提供所需的东西,但它包含一些 PyLint 工作的解决方法。如果您可以使用我在开始时解释的推荐方式,请改用它。

关于python-3.x - 如何在 VS Code 中正确导入 Python 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59702230/

相关文章:

python - 如何从无限生成器中干净地捕获?

go - 如何调试特定功能?

c# - Visual Studio Code C# 调试问题(终端进程无法启动 : Path to shell executable "dotnet" is not a file of a symlink.)

python - 如何基于其他列在 Python 中创建排名列

python - 安装Anaconda后在Linux Mint中配置python3指向/usr/bin/python3.8

python - Pylint 未检测到 'else' 子句中的 undefined variable

python - 如何在 Python 中指示多个未使用的值?

python - Python 标准库代码 Pylint 评分低的原因

python - 基方法和子方法签名中的参数数量不一致

visual-studio-code - Prettier 格式在具有最新 Prettier 扩展版本 (v7.1.0) 的 Mac 上不起作用