run python code from c# does not return a value

折月煮酒 提交于 2021-01-07 01:41:54

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/65390092/run-python-code-from-c-sharp-does-not-return-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!