问题描述
我将 Visual Studio Code 与 Python 插件和 autopep8 一起使用:
I'm using Visual Studio Code with the Python plugin and autopep8 with:
"editor.formatOnSave": true
我有需要导入的本地包,所以我有类似的东西:
I have local packages I need to import, so I have something like:
import sys
sys.path.insert(0, '/path/to/packages')
import localpackage
但是当我保存时,Visual Studio Code/autopep8 将所有导入语句移到代码之前,因此 Python 找不到我的本地包.
but when I save, Visual Studio Code/autopep8 moves all import statements before the code, so Python can't find my local package.
import sys
import localpackage
sys.path.insert(0, '/path/to/packages')
我如何告诉 Visual Studio Code/autopep8 在导入之前放置一个语句是可以的,或者是否有更正确的导入本地包的方法?
How can I tell Visual Studio Code/autopep8 that it's okay to put a statement before imports, or is there a more correct way of importing local packages?
作为一种解决方法,如果您在 if 语句中导入似乎没问题:
As a workaround, it looks like it's fine if you import in an if statement:
import sys
sys.path.insert(0, '/path/to/packages')
if 'localpackage' not in sys.modules:
import localpackage
推荐答案
打开设置
Open settings
搜索 autopep8.您应该会看到以下结果:
Search for autopep8. You should see the following results:
点击在 settings.json 中编辑";在第一个选项下
Click on "Edit in settings.json" under the first option
将以下参数添加到用户设置 JSON 文件中:
Add the following argument to the User Settings JSON file:
"python.formatting.autopep8Args": ["--ignore", "E402"]
这告诉 autopep8
忽略错误 402,即:模块级导入不在文件顶部"(这是 pep8 中的 错误列表)
This tells autopep8
to ignore error 402 which is: "module level import not at top of file" (here's the list of errors in pep8)
您可以使用相同的方法更改任何 autopep8
设置.例如,如果您只想修复缩进,您可以使用 "python.formatting.autopep8Args": ["--select", "E1"]
You can use this same method to change any of the autopep8
settings. For example, if you only wanted to fix indentation, you can use "python.formatting.autopep8Args": ["--select", "E1"]
autopep8 自述文件 提供了有关可用选项的更多信息.
The autopep8 readme has more information on the available options.
这篇关于在使用 Visual Studio Code 和 autopep8 导入之前允许语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!