【问题标题】:How to return the "return value" of a python script in C#?如何在 C# 中返回 python 脚本的“返回值”?
【发布时间】:2020-07-31 08:25:11
【问题描述】:

我想在 C# 中运行一个 python 脚本,然后想将 python 脚本的“返回值”返回到 C#。

我的python脚本:

def myfunc():
    print("aaa")
    return "abc"

if __name__ == "__main__":
     myfunc()

我的 C# 文件:

void Main()
{
    var result = run_cmd();
    Console.WriteLine(result);
}


private string run_cmd()
{

    string fileName = @"C:\Users\NCH-Lap10\Desktop\return_one.py";
    string python = @"C:\Users\NCH-Lap10\AppData\Local\Programs\Python\Python37-32\python.exe";

    Process psi = new Process();
    psi.StartInfo = new ProcessStartInfo(python, fileName)
    {
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = false
    };
    psi.Start();

    string output = psi.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    
    psi.WaitForExit();
    int result = psi.ExitCode;
        
    return output;
}

我可以返回打印的消息“aaa”,但我需要“abc”。我认为 psi.ExitCode 会给我所需的输出,但它不起作用。

【问题讨论】:

  • 我认为,您需要一个嵌入式 Python 解释器。如果您的数据简单且可序列化,请考虑使用套接字传递数据。

标签: python c# return-value processstartinfo


【解决方案1】:

您的脚本仅在内部返回 myfunc 的值。 如果要导出值,可以在main-if后面写print(myfunc())。 还请查看此answer,因为它讨论了各种方法和概念

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2012-08-07
    • 2018-06-25
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多