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

从C#调用Python脚本时如何获取Python的输出值

问题描述

我在C#应用中调用Python脚本执行,使用的C#代码如下:

string srCommandName = "customWhisper.py D:\Tas\Monitor\Stemme_226.m4a 41f850e7-455e-4f84-b1eb-a5cccea49046.txt"
ProcessStartInfo psInfo = new ProcessStartInfo(srCommandName);
psInfo.UseShellExecute= false;
psInfo.RedirectStandardOutput = true;
using (Process process = Process.Start(psInfo))
{
    using (StreamReader reader = process.StandardOutput)
    {
        string result = reader.ReadToEnd();
        if (result=="")
        { }
    }
}

对应的Python代码如下:

import sys
import os
import whisper

try:   
  if len(sys.argv)==3:
    mediaPath = sys.argv[1] 
    textFilePath = sys.argv[2]
    model = whisper.load_model("tiny")
    isExist = os.path.exists(mediaPath)    
    if isExist:
        results = model.transcribe(mediaPath, language = "da")
        stab_segments = results['segments']
        text_file = open(textFilePath, "w",encoding="utf-8")
        for i in stab_segments:
           text_file.write(i["text"] + '\n')
        text_file.close()
        print(0)
    else:
        print(1)
  else:
    print(len(sys.argv))
except Exception as er:
    print(er)

我期望通过string result = reader.ReadToEnd();获取Python打印的0(成功时)、1或其他异常信息,但实际得到的是srCommandName的值,请问如何让C#正确获取Python返回的输出值?

解决方法
  • 修正进程启动逻辑:直接把脚本文件作为启动命令,系统无法自动关联Python解释器执行脚本。需要将Python可执行文件设为启动程序,脚本路径和参数放到Arguments属性中,同时注意C#里路径的转义(用\\或@字符串避免转义问题)。

  • 等待进程执行完成:读取输出前必须调用WaitForExit(),确保Python脚本完全执行完毕,避免因进程未结束导致读取不完整或为空。

  • 重定向错误输出:建议同时开启RedirectStandardError,可以捕获Python脚本的异常信息,也能避免进程因错误输出缓冲而挂起。

  • 禁用Python输出缓冲:Python的print默认会缓冲输出,可在启动参数中添加-u参数禁用缓冲,确保输出能实时传递给C#。

修改后的C#代码示例:

// 使用@字符串简化路径书写,避免转义
string scriptPath = @"customWhisper.py";
string mediaPath = @"D:\Tas\Monitor\Stemme_226.m4a";
string textFilePath = @"41f850e7-455e-4f84-b1eb-a5cccea49046.txt";

ProcessStartInfo psInfo = new ProcessStartInfo("python.exe")
{
    Arguments = $"-u \"{scriptPath}\" \"{mediaPath}\" \"{textFilePath}\"",
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true
};

using (Process process = Process.Start(psInfo))
{
    // 先读错误输出,避免进程阻塞
    string errorMsg = process.StandardError.ReadToEnd();
    // 读取标准输出
    string result = process.StandardOutput.ReadToEnd();
    // 等待进程执行结束
    process.WaitForExit();

    // 处理获取到的内容
    if (!string.IsNullOrWhiteSpace(result))
    {
        // 这里可以处理Python返回的0、1等结果
        Console.WriteLine($"Python输出结果: {result}");
    }
    if (!string.IsNullOrWhiteSpace(errorMsg))
    {
        Console.WriteLine($"Python错误信息: {errorMsg}");
    }
}

补充说明:

  • 若系统中Python可执行文件名为python3.exe(如Linux/macOS环境或多版本Python共存场景),需替换为对应名称。
  • 确保Python脚本中已引入所有必要模块(原代码缺少import sys、import os、import whisper,需补充)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:20:21