You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB .NET 4.5调用Python脚本遇文件未找到报错及进程执行失效求助

VB.NET调用Python脚本遇文件未找到/未执行问题的解决办法

问题现象

运行以下VB.NET代码时抛出System.IO.FileNotFoundException: File not found错误:

Sub Main()
        Dim scriptPath As String = "D:\Programs\Tester.py"
        Dim pythonPath As String = "D:\anaconda3\python.exe"
        If IO.File.Exists(scriptPath) Then
            Shell(pythonPath + " " + scriptPath)
        End If
End Sub
  • IO.File.Exists能正常检测到脚本文件存在,但执行Shell调用时却报文件未找到
  • 改用Process类调用时无报错,但Python脚本并未实际执行
  • 路径均从文件属性复制确认无误,手动在命令行执行python D:\Programs\Tester.py可正常运行脚本

解决步骤

1. 为路径添加双引号(解决Shell调用的核心问题)

即使当前路径不含空格,Shell解析命令时也可能因特殊字符或上下文歧义导致路径识别失败,给Python可执行文件路径和脚本路径都加上双引号:

Sub Main()
        ' 直接在字符串中嵌入双引号
        Dim scriptPath As String = """D:\Programs\Tester.py"""
        Dim pythonPath As String = """D:\anaconda3\python.exe"""
        ' 检测文件时需先移除引号
        If IO.File.Exists(scriptPath.Replace("""", "")) Then
            Shell(pythonPath & " " & scriptPath)
        End If
End Sub

也可以用字符串插值动态添加引号,更易读:

Dim quotedPythonPath = $" ""{pythonPath}"" "
Dim quotedScriptPath = $" ""{scriptPath}"" "
Shell(quotedPythonPath & quotedScriptPath)

2. 改用Process类并正确配置参数(更稳定的调用方式)

之前Process类调用失效,大概率是参数或启动信息配置错误,以下是经过验证的正确示例:

Sub Main()
    Dim scriptPath As String = "D:\Programs\Tester.py"
    Dim pythonPath As String = "D:\anaconda3\python.exe"

    If IO.File.Exists(scriptPath) Then
        Dim startInfo As New ProcessStartInfo With {
            .FileName = pythonPath,
            .Arguments = scriptPath,
            .UseShellExecute = False,
            .RedirectStandardOutput = True,
            .RedirectStandardError = True,
            .CreateNoWindow = False ' 设为True可隐藏命令行窗口
        }

        Using proc As New Process()
            proc.StartInfo = startInfo
            proc.Start()

            ' 捕获输出和错误信息,方便排查问题
            Dim output As String = proc.StandardOutput.ReadToEnd()
            Dim errorMsg As String = proc.StandardError.ReadToEnd()
            proc.WaitForExit()

            ' 可将结果输出到控制台或日志文件
            Console.WriteLine("脚本输出:" & output)
            Console.WriteLine("错误信息:" & errorMsg)
        End Using
    End If
End Sub
  • 关键配置:UseShellExecute = False让系统直接调用可执行文件,避免Shell解析的不确定性;
  • 重定向输出流可以帮你确认脚本是否真的执行,以及捕获脚本内部的报错;
  • WaitForExit()确保VB.NET程序等待Python脚本执行完成后再继续。

3. 排查权限与运行上下文

  • 确保VB.NET程序的运行权限和手动执行Python脚本时的权限一致(比如不要混用管理员/普通用户身份);
  • 检查VB.NET项目的目标平台(x86/x64)是否与Python安装版本匹配,64位Python对应64位VB.NET项目,32位同理,避免跨位数调用导致的隐性错误。

内容的提问来源于stack exchange,提问作者pm233

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:06:11