如何在VSCode中配置自定义Python代码格式化工具及执行顺序?
配置自定义Python格式化工具到VSCode
步骤1:将自定义函数封装为可执行脚本
首先需要把align_assignment_expressions函数包装成能处理标准输入输出的Python脚本——VSCode的格式化工具是通过外部程序读取待格式化代码、输出结果的。
创建名为custom_formatter.py的脚本,内容如下:
import sys # 替换成你的格式化函数所在的模块路径 from your_formatter_module import align_assignment_expressions def main(): # 从标准输入读取原始代码 raw_code = sys.stdin.read() # 调用自定义格式化逻辑 formatted_code = align_assignment_expressions(raw_code) # 将格式化结果输出到标准输出 sys.stdout.write(formatted_code) if __name__ == "__main__": main()
确保脚本所在的Python环境能正常导入你的格式化函数,Linux/macOS用户可执行chmod +x custom_formatter.py给脚本添加可执行权限。
步骤2:配置VSCode使用自定义格式化工具
打开VSCode用户设置(快捷键Ctrl+,),点击右上角的{}图标打开settings.json,添加以下配置:
{ "[python]": { "editor.defaultFormatter": "ms-python.python", // 可选:开启保存时自动格式化 "editor.formatOnSave": true }, "python.formatting.provider": "custom", // 替换为你的Python解释器路径(比如虚拟环境的python.exe/python) "python.formatting.customFormatterPath": "python", // 替换为custom_formatter.py的绝对路径 "python.formatting.customFormatterArgs": [ "/full/path/to/your/custom_formatter.py" ] }
配置完成后,按下对应系统的格式化快捷键(Windows:Shift+Alt+F,Linux:Ctrl+Shift+I),VSCode就会调用你的自定义工具处理当前文件。
进阶:先运行Black再执行自定义脚本
如果需要先通过Black完成基础格式化,再用你的工具做调整,需要写一个串联两个工具的包装脚本。
创建black_plus_custom.py脚本,内容如下:
import sys import subprocess # 替换成你的格式化函数所在模块 from your_formatter_module import align_assignment_expressions def main(): raw_code = sys.stdin.read() # 调用Black做基础格式化 try: black_result = subprocess.run( ["black", "-", "--quiet"], input=raw_code.encode("utf-8"), capture_output=True, check=True ) black_formatted = black_result.stdout.decode("utf-8") except subprocess.CalledProcessError as e: # Black报错时,输出原代码和错误信息 sys.stderr.write(e.stderr.decode("utf-8")) sys.stdout.write(raw_code) return # 用自定义工具二次格式化 final_code = align_assignment_expressions(black_formatted) sys.stdout.write(final_code) if __name__ == "__main__": main()
然后修改VSCode的settings.json,把python.formatting.customFormatterArgs指向这个包装脚本:
"python.formatting.customFormatterArgs": [ "/full/path/to/your/black_plus_custom.py" ]
注意:确保你的Python环境已安装Black(执行pip install black),且black命令能在VSCode使用的解释器环境中正常调用。
内容的提问来源于stack exchange,提问作者Joe Boyle
相关产品推荐
相关产品推荐

