简体   繁体   English

通过C#执行时从Python个文件中获取output

[英]Getting output from Python files when executed through C#

Im calling Python script from a C# app to execute with the code below我从 C# 应用程序调用 Python 脚本以使用以下代码执行

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=="")
        { }
    }
}

My Python code is:我的 Python 代码是:

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)

The desired output from string result = reader.ReadToEnd();所需的 output 来自 string result = reader.ReadToEnd(); should had been 0 (print 0) on success or one of the other prints.成功时应该是 0(打印 0)或其他打印之一。 But its the srCommandName但它的 srCommandName

Is there any way to get Python to return a value when called from C#从 C# 调用时,有什么方法可以让 Python 返回一个值

I use the below method to call python script from c# and get the result from python standard output back as a string.我使用以下方法从 c# 调用 python 脚本,并从 python 标准 output 获取结果作为字符串返回。 The FileName property of ProcessStartInfo should point to the python interpreter to use - not the python script. ProcessStartInfoFileName属性应指向要使用的 python 解释器,而不是 python 脚本。 The python script should be sent as first argument. python 脚本应作为第一个参数发送。

   private (string output, int exitCode) RunPythonScript(string pathToPythonFile, string args)
    {
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"C:\MyPathToPythonInterpreter\Scripts\python.exe";
        start.Arguments = string.Format("{0} {1}", pathToPythonFile, args);
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            process.WaitForExit();

            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                return (result, process.ExitCode);
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM