0

Good day! I was recommended to try an approach to allow c# to run python code and then the python output would be sent to the c# program where it could be used.

see Link for examples: How do I run a Python script from C#?

My implementation:

 private void run_cmd()
        {
            
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = "Path\\To\\python.exe";
            start.Arguments = "Path\\To\\Thing.py";
            ;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {

                    string result = reader.ReadToEnd();
                    if (result.Equals("-1.0"))
                    {
                        Print("Hello");
                    }
                    else if (result.Equals("1.0"))
                    {
                        Print("Hello");
                    }
                    process.WaitForExit();
                    //Print(result);
                }
            }
        }

I implemented this and it works well however I am not getting the output from my python program back into the c# program, the c# program does not print out "Hello" at all(The print command is valid for the platform I am using).

The following is a print statement on which I tried to test it.

        print(1.0)

but there is no output given.

Any help would be appreciated.

  • I think your arguments are wrong. `start.Arguments = string.Format("{0} {1}", "Path\\To\\Thing.py", start.FileName);` should be `start.Arguments = "Path\\To\\Thing.py"`. Because as it is right now the command being executed in the shell is `Path\\To\\python.exe Path\\To\\Thing.py Path\\To\\python.exe` – MindSwipe Dec 21 '20 at 09:18
  • Okay I have changed it on my program. So I will edit the Question in this way. Thank you – Leon Von Moltke Dec 21 '20 at 09:26
  • Add a '\0' to the python output. ReadToEnd isn't recognizing the python is completed and waiting for an end. – jdweng Dec 21 '20 at 09:26
  • I tried this and edited my if statement in the following way, if (result.Equals("1.0 \0") however this did not work. When Python printed ("1.0 \0"). – Leon Von Moltke Dec 21 '20 at 09:30

1 Answers1

0

The mistake I made was to choose the wrong python.exe file to run it from. I later changed this path to the Path\To\python3.8.exe and after installing all the correct packages the problem was solved a very helpful guide was printing out the error which is set

error = process.StandardError.ReadToEnd();

And this allowed me to find my mistake