如何程序化控制VS Code AI扩展提取补全建议并保存至文件?
用Python自动化VS Code中AI扩展的代码补全任务
方案一:轻量实现(CLI+键盘模拟)
依赖准备
- 安装Python库:
pyautogui(模拟键盘操作)、psutil(检查VS Code进程)pip install pyautogui psutil - 确保VS Code已安装
GitHub Copilot和huggingface-vscode扩展,且完成登录授权
Python脚本实现
脚本完成以下操作:加载项目、定位到指定光标位置、触发补全、收集当前选中的补全结果并保存。
import os import time import pyautogui import psutil from subprocess import Popen, call # 配置参数 PROJECT_PATH = "/path/to/your/project" TARGET_FILE = "src/main.py" TARGET_LINE = 42 # 行号从1开始 TARGET_COL = 10 # 列号从1开始 COMPLETION_SAVE_PATH = "completion_results.txt" # 根据系统调整VS Code路径:Windows用"code.exe",Mac用"/Applications/Visual Studio Code.app/Contents/MacOS/Electron" VSCODE_PATH = "code" def check_vscode_running(): for proc in psutil.process_iter(['name']): if proc.info['name'] in ['Code', 'code.exe', 'Electron']: return True return False def main(): # 启动VS Code并加载项目 if not check_vscode_running(): Popen([VSCODE_PATH, PROJECT_PATH]) time.sleep(5) # 等待VS Code加载完成 # 打开目标文件并定位到指定位置 call([VSCODE_PATH, "--goto", f"{os.path.join(PROJECT_PATH, TARGET_FILE)}:{TARGET_LINE}:{TARGET_COL}"]) time.sleep(2) # 等待文件打开并定位 # 触发GitHub Copilot补全(默认快捷键Ctrl+Enter,Mac替换为Cmd+Enter) pyautogui.hotkey('ctrl', 'enter') time.sleep(3) # 等待补全结果加载 pyautogui.hotkey('ctrl', 'a') pyautogui.hotkey('ctrl', 'c') with open(COMPLETION_SAVE_PATH, 'w', encoding='utf-8') as f: f.write(pyautogui.paste()) # 触发Hugging Face补全(默认快捷键Ctrl+Space,Mac替换为Cmd+Space) pyautogui.hotkey('ctrl', 'space') time.sleep(3) pyautogui.hotkey('ctrl', 'a') pyautogui.hotkey('ctrl', 'c') with open(COMPLETION_SAVE_PATH, 'a', encoding='utf-8') as f: f.write("\n--- Hugging Face 补全结果 ---\n") f.write(pyautogui.paste()) if __name__ == "__main__": main()
注意事项
- 需根据系统调整VS Code路径和快捷键组合
- 等待时间需根据项目大小、网络情况调整,避免因加载不充分导致失败
- 模拟键盘操作依赖VS Code处于前台焦点,运行时不要切换窗口
- 该方案仅能收集当前选中的补全内容,若需获取所有补全候选,建议使用方案二
方案二:稳定实现(自定义VS Code扩展+Python调用)
核心思路
编写极简VS Code扩展,通过官方API暴露触发补全、收集结果的命令,再用Python调用VS Code CLI触发这些命令,完全避免模拟输入的不稳定问题。
步骤1:编写并安装自定义扩展
- 初始化扩展项目:
npm install -g yo generator-code yo code # 选择New Extension (TypeScript) - 修改
extension.ts,添加触发补全并保存结果的命令:import * as vscode from 'vscode'; import * as fs from 'fs'; export function activate(context: vscode.ExtensionContext) { // 触发GitHub Copilot补全并保存结果 const copilotCmd = vscode.commands.registerCommand('auto-completion.copilot', async () => { const editor = vscode.window.activeTextEditor; if (!editor) { return; } // 调用Copilot内置生成命令 await vscode.commands.executeCommand('github.copilot.generate'); await new Promise(resolve => setTimeout(resolve, 2000)); // 获取当前编辑器内容(含补全结果) const content = editor.document.getText(); fs.writeFileSync('copilot_completion.txt', content, 'utf-8'); }); // 触发Hugging Face补全并保存结果 const hfCmd = vscode.commands.registerCommand('auto-completion.huggingface', async () => { const editor = vscode.window.activeTextEditor; if (!editor) { return; } // 调用Hugging Face内置补全命令 await vscode.commands.executeCommand('huggingface.complete'); await new Promise(resolve => setTimeout(resolve, 2000)); const content = editor.document.getText(); fs.writeFileSync('hf_completion.txt', content, 'utf-8'); }); context.subscriptions.push(copilotCmd, hfCmd); } export function deactivate() {} - 打包并安装扩展:
在VS Code扩展面板选择「Install from VSIX...」,选择生成的文件完成安装。npm install -g vsce vsce package # 生成.vsix格式扩展包
步骤2:Python脚本调用扩展命令
import os from subprocess import call # 配置参数 PROJECT_PATH = "/path/to/your/project" TARGET_FILE = "src/main.py" TARGET_LINE = 42 TARGET_COL = 10 def main(): # 打开项目并定位到指定光标位置 call([ "code", PROJECT_PATH, "--goto", f"{os.path.join(PROJECT_PATH, TARGET_FILE)}:{TARGET_LINE}:{TARGET_COL}" ]) # 触发Copilot补全命令 call(["code", "--command", "auto-completion.copilot"]) # 触发Hugging Face补全命令 call(["code", "--command", "auto-completion.huggingface"]) if __name__ == "__main__": main()
优势
- 基于VS Code官方API实现,稳定性高,不依赖窗口焦点
- 可精确控制补全触发逻辑,若需收集所有补全候选,可进一步扩展监听补全事件的代码
- 易于扩展更多自动化操作
内容的提问来源于stack exchange,提问作者Exploring
相关产品推荐
相关产品推荐

