如何从C#运行Python脚本?

发布于 2021-02-02 23:19:44

之前曾在不同程度上提出过这样的问题,但我觉得还没有以简明的方式回答,因此我再次提出。

我想在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);
            }
        }
    }

当我传递code.py位置as cmdfilename位置as args无效时。有人告诉我,我应该通过python.execmd,然后code.py filename作为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);
        }
    }
关注者
0
被浏览
109
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

    如果不使用外壳程序,则必须以方式提供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);
             }
         }
    }
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看