运行C#中的python脚本 [英] run a python script from c#

查看:330
本文介绍了运行C#中的python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类问题已经问过不同程度的,但我觉得它没有在一个简洁的方式回答,所以我再问吧。

我想运行在Python脚本,让我们说这是这样的:

 如果__name__ =='__main__':
    F =开(sys.argv中[1],R)
    S = f.read()
    f.close()
    打印■
 

它得到一个文件的位置,读取它,然后打印出它的内容。没有那么复杂。

好了,让我怎么跑这在C#?

这是我现在有:

 私人无效RUN_CMD(字符串CMD,字符串参数)
    {
        的ProcessStartInfo开始=新的ProcessStartInfo();
        start.FileName = CMD;
        start.Arguments = ARGS;
        start.UseShellExecute = FALSE;
        start.RedirectStandardOutput =真;
        使用(工艺过程=的Process.Start(开始))
        {
            使用(StreamReader的读卡器= process.StandardOutput)
            {
                字符串结果= reader.ReadToEnd();
                Console.Write(结果);
            }
        }
    }
 

当我通过 code.py 位置 CMD 文件名位置的args 它不工作。有人告诉我,我应该通过 python.exe CMD ,然后 code.py文件名的args

我一直在寻找了一段时间,现在,只能找人建议使用IronPython的或此类。但是,必须有一个方法来调用从C#的Python脚本。

一些澄清:

我需要从C#运行它,我需要捕捉输出,而我不能使用IronPython的或其他任何东西。无论砍你会被罚款。

P.S。实际的蟒蛇code我跑的比这要复杂得多,它返回的输出,我需要在C#和C#code会不断地调用了Python。

pretend这是我的code:

 私人无效get_vals()
    {
        的for(int i = 0; I< 100;我++)
        {
            RUN_CMD(code.py,我);
        }
    }
 

解决方案

它不工作的原因是因为你有 UseShellExecute =假

如果您不使用shell,则必须提供完整路径蟒蛇可执行文件文件名,并建立了参数字符串,同时提供你的脚本,你想阅读该文件。

另外请注意,你不能 RedirectStandardOutput 除非 UseShellExecute =假

我不太清楚如何将参数字符串格式应为蟒蛇,但你需要的东西是这样的:

 私人无效RUN_CMD(字符串CMD,字符串参数)
{
     的ProcessStartInfo开始=新的ProcessStartInfo();
     start.FileName =我/全速/路径/到/ python.exe;
     start.Arguments =的String.Format({0} {1},CMD,参数);
     start.UseShellExecute = FALSE;
     start.RedirectStandardOutput =真;
     使用(工艺过程=的Process.Start(开始))
     {
         使用(StreamReader的读卡器= process.StandardOutput)
         {
             字符串结果= reader.ReadToEnd();
             Console.Write(结果);
         }
     }
}
 

This sort of question has been asked before in varying degrees, but I feel it has not been answered in a concise way and so I ask it again.

I want to run a script in Python, let's say it's this:

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

Which gets a file location, reads it, then prints its contents. Not so complicated.

Okay, so how do I run this in C#?

This is what I have now:

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

When I pass the code.py location as cmd and the filename location as args it doesnt work. I was told I should pass python.exe as the cmd, and then code.py filename as the args.

I have been looking for a while now, and can only find people suggesting to use IronPython or such. But there must be a way to call a Python script from C#.

Some clarification:

I need to run it from C#, I need to capture the output, and I can't use IronPython or anything else. Whatever hack you have will be fine.

P.S. The actual python code I'm running is much more complex than this, and it returns output which I need in C#, and the C# code will be constantly calling the Python.

Pretend this is my code:

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

解决方案

The reason it isn't working is because you have UseShellExecute = false.

If you don't use the shell, you will have to supply the complete path to the python executable as FileName, and build the Arguments string to supply both your script and the file you want to read.

Also note, that you can't RedirectStandardOutput unless UseShellExecute = false.

I'm not quite sure how the argument string should be formatted for python, but you will need something like this:

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

这篇关于运行C#中的python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆