如何从 C# 运行 Python 脚本?

新手上路,请多包涵

这种问题以前也有不同程度的问过,但感觉没有得到简洁的回答,所以再问一次。

我想在 Python 中运行脚本。假设是这样的:

 if __name__ == '__main__':
    with open(sys.argv[1], 'r') as f:
        s = f.read()
    print s

它获取文件位置,读取它,然后打印其内容。没那么复杂。

好的,那么我如何在 C# 中运行它呢?

这就是我现在所拥有的:

     private void run_cmd(string cmd, string args)
    {
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = cmd;
        start.Arguments = args;
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
    }

当我通过 filename code.py 位置为 cmd args I was told I should pass python.exe as the cmd , and then code.py filename as the args .

我已经找了一段时间了,只能找到建议使用 IronPython 之类的人。但是必须有一种方法可以从 C# 调用 Python 脚本。

一些说明:

我需要从 C# 运行它,我需要捕获输出,我不能使用 IronPython 或其他任何东西。无论你有什么技巧都可以。

PS:我运行的实际 Python 代码比这复杂得多,它返回我在 C# 中需要的输出,C# 代码将不断调用 Python 代码。

假装这是我的代码:

     private void get_vals()
    {
        for (int i = 0; i < 100; i++)
        {
            run_cmd("code.py", i);
        }
    }

原文由 Inbar Rose 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 335
2 个回答

它不起作用的原因是因为您有 UseShellExecute = false

如果不使用 shell,则必须提供 python 可执行文件的完整路径 FileName ,并构建 Arguments 字符串以提供脚本和文件想读。

另请注意,您不能 RedirectStandardOutput 除非 UseShellExecute = false

我不太确定应该如何为 python 设置参数字符串的格式,但你需要这样的东西:

 private void run_cmd(string cmd, string args)
{
     ProcessStartInfo start = new ProcessStartInfo();
     start.FileName = "my/full/path/to/python.exe";
     start.Arguments = string.Format("{0} {1}", cmd, args);
     start.UseShellExecute = false;
     start.RedirectStandardOutput = true;
     using(Process process = Process.Start(start))
     {
         using(StreamReader reader = process.StandardOutput)
         {
             string result = reader.ReadToEnd();
             Console.Write(result);
         }
     }
}

原文由 Master Morality 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你愿意使用 IronPython,你可以直接在 C# 中执行脚本:

 using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

在此处获取 IronPython。

原文由 Chris Dunaway 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏