如何从C#运行Python脚本?

2024-04-24 04:05:59 发布

您现在位置: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);
            }
        }
    }

当我将code.py位置作为cmd传递,将filename位置作为args传递时,它不起作用。有人告诉我应该把python.exe作为cmd,然后把code.py filename作为args

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

一些澄清:

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

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

假装这是我的密码:

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

Tags: runpy脚本cmdstringargscodeprivate
3条回答

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

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

还要注意,除非UseShellExecute = false,否则不能RedirectStandardOutput

我不太确定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);
         }
     }
}

从C

执行Python脚本

创建一个C#项目并编写以下代码。

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            run_cmd();
        }

        private void run_cmd()
        {

            string fileName = @"C:\sample_script.py";

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            p.Start();

            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            Console.WriteLine(output);

            Console.ReadLine();

        }
    }
}

Python示例脚本

print "Python C# Test"

您将在C的控制台中看到“Python C#Test”。

如果您愿意使用IronPython,可以直接在C#:

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

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

Get IronPython here.

相关问题 更多 >