【问题标题】:run python code from c# does not return a value从c#运行python代码不返回值
【发布时间】:2021-03-31 01:24:37
【问题描述】:

美好的一天! 有人建议我尝试一种方法,让 c# 运行 python 代码,然后将 python 输出发送到可以使用它的 c# 程序。

示例见链接:How do I run a Python script from C#?

我的实现:

 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);
                }
            }
        }

我实现了这个并且效果很好但是我没有将我的 python 程序的输出返回到 c# 程序中,c# 程序根本不会打印出“Hello”(打印命令对我所在的平台有效使用)。

以下是我尝试测试的打印语句。

        print(1.0)

但没有给出输出。

任何帮助将不胜感激。

【问题讨论】:

  • 我认为你的论点是错误的。 start.Arguments = string.Format("{0} {1}", "Path\\To\\Thing.py", start.FileName); 应该是 start.Arguments = "Path\\To\\Thing.py"。因为现在在shell中执行的命令是Path\\To\\python.exe Path\\To\\Thing.py Path\\To\\python.exe
  • 好的,我已经在我的程序上更改了它。所以我将以这种方式编辑问题。谢谢
  • 在 python 输出中添加一个 '\0'。 ReadToEnd 无法识别 python 已完成并等待结束。
  • 我尝试了这个并以下列方式编辑了我的 if 语句,if (result.Equals("1.0 \0") 但这不起作用。当 Python 打印时 ("1.0 \0")。

标签: python c# return connection ironpython


【解决方案1】:

我犯的错误是选择了错误的 python.exe 文件来运行它。我后来将此路径更改为 Path\To\python3.8.exe 并在安装所有正确的软件包后问题得到解决,一个非常有用的指南打印出设置的错误

error = process.StandardError.ReadToEnd();

这让我发现了自己的错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多