如何在Visual Studio 2019打开解决方案时自动运行Python脚本?
解决方案:VS2019打开解决方案时自动执行Python维护脚本
方案一:使用VS宏(快速实现,无需编写复杂扩展)
- 安装宏扩展:打开VS2019的扩展管理器(工具->扩展和更新),搜索安装「Macros for Visual Studio 2019」。
- 打开宏编辑器:点击「视图->其他窗口->宏资源管理器」。
- 创建宏模块:右键「MyMacros」,选择「添加模块」,命名为
SolutionAutoRun。 - 粘贴以下宏代码:
Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Imports System.IO Public Module SolutionAutoRun Dim WithEvents solEvents As SolutionEvents Sub Init() solEvents = DTE.Events.SolutionEvents End Sub Private Sub solEvents_Opened() Handles solEvents.Opened ' 获取当前解决方案的目录 Dim solutionDir As String = Path.GetDirectoryName(DTE.Solution.FullName) ' 替换为你的Python脚本文件名 Dim scriptPath As String = Path.Combine(solutionDir, "maintain.py") ' 检查脚本是否存在,避免报错 If File.Exists(scriptPath) Then Dim process As New Process() ' 如果Python不在系统PATH中,替换为python.exe的完整路径(如"C:\Python310\python.exe") process.StartInfo.FileName = "python.exe" process.StartInfo.Arguments = $"""{scriptPath}""" process.StartInfo.WorkingDirectory = solutionDir ' 若不需要显示Python控制台窗口,取消下方注释 ' process.StartInfo.CreateNoWindow = True ' process.StartInfo.UseShellExecute = False process.Start() End If End Sub End Module
- 设置启动自动运行:在宏资源管理器中右键
SolutionAutoRun模块,选择「添加到启动项」。
此后每次打开VS并加载解决方案时,宏会自动检测同目录下的Python脚本并执行。
方案二:自定义VS扩展(长期稳定方案)
适合需要更稳定、无依赖的场景:
- 安装扩展开发工作负载:打开VS安装器,修改安装,勾选「Visual Studio Extension Development」工作负载。
- 创建VSIX项目:新建项目,选择「Visual C#->Extensibility->VSIX Project」,命名为
AutoRunPythonScript。 - 添加引用:右键项目->添加引用,勾选
EnvDTE和EnvDTE80。 - 修改Package类代码:替换
AutoRunPythonScriptPackage.cs中的内容为:
using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using System; using System.Diagnostics; using System.IO; namespace AutoRunPythonScript { [PackageRegistration(UseManagedResourcesOnly = true)] [Guid("F1234567-ABCD-1234-EFGH-1234567890AB")] // 替换为生成的GUID(工具->创建GUID) public sealed class AutoRunPythonScriptPackage : Package { private DTE2 _dte; private SolutionEvents _solutionEvents; protected override void Initialize() { base.Initialize(); _dte = GetService(typeof(DTE)) as DTE2; _solutionEvents = _dte.Events.SolutionEvents; _solutionEvents.Opened += OnSolutionOpened; } private void OnSolutionOpened() { string solutionDir = Path.GetDirectoryName(_dte.Solution.FullName); string scriptPath = Path.Combine(solutionDir, "maintain.py"); if (File.Exists(scriptPath)) { var startInfo = new ProcessStartInfo { FileName = "python.exe", // 替换为Python完整路径(若不在PATH中) Arguments = $"\"{scriptPath}\"", WorkingDirectory = solutionDir, CreateNoWindow = true, // 隐藏控制台窗口 UseShellExecute = false }; Process.Start(startInfo); } } } }
- 生成并安装扩展:编译项目,找到输出目录中的
.vsix文件,双击安装到VS2019。
安装完成后,每次打开解决方案都会自动执行同目录下的Python脚本。
注意事项
- 确保Python已添加到系统PATH,否则需在代码中指定
python.exe的完整路径。 - 若脚本需要管理员权限,需修改ProcessStartInfo添加
Verb = "runas"(慎用,会弹出UAC提示)。
内容的提问来源于stack exchange,提问作者winsett
相关产品推荐
相关产品推荐

