0

Im calling Python script from a C# app to execute with the code below

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:

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(); should had been 0 (print 0) on success or one of the other prints. But its the srCommandName

Is there any way to get Python to return a value when called from C#

1 Answer 1

1

I use the below method to call python script from c# and get the result from python standard output back as a string. The FileName property of ProcessStartInfo should point to the python interpreter to use - not the python script. The python script should be sent as first argument.

   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);
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.