繁体   English   中英

如何从 C# 运行 Python 脚本?

[英]How do I run a Python script from C#?

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

我想在 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# 运行它,我需要捕获 output,我不能使用 IronPython 或其他任何东西。 无论你有什么技巧都可以。

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

假装这是我的代码:

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

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

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

另请注意,除非UseShellExecute = false否则您不能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);
         }
     }
}

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

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

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

在此处获取 IronPython。

从 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 sample_script

print "Python C# Test"

您将在C#的控制台中看到“Python C# 测试”

我遇到了同样的问题,道德大师的回答对我不起作用。 以下基于之前的答案,有效:

private void run_cmd(string cmd, string args)
{
 ProcessStartInfo start = new ProcessStartInfo();
 start.FileName = cmd;//cmd is full path to python.exe
 start.Arguments = args;//args is path to .py file and any cmd line 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);
     }
 }
}

例如,如果您想使用 cmd 行参数 100 执行 test.py,则 cmd 将是@C:/Python26/python.exe并且 args 将是C://Python26//test.py 100 100。请注意路径.py 文件没有 @ 符号。

也是为了提请您注意这一点:

https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee

它工作得很好。

实际上,使用 IronPython 在 Csharp (VS) 和 Python 之间进行集成非常容易。 它并没有那么复杂......正如 Chris Dunaway 在回答部分已经说过的那样,我开始为我自己的项目构建这种集成。 N 很简单。 只需按照这些步骤 N 你就会得到你的结果。

第 1 步:打开 VS 并创建新的空 ConsoleApp 项目。

第 2 步:转到工具 --> NuGet 包管理器 --> 包管理器控制台。

第 3 步:在此之后,在浏览器中打开此链接并复制 NuGet 命令。 链接: https : //www.nuget.org/packages/IronPython/2.7.9

第 4 步:打开上述链接后,复制 PM>Install-Package IronPython -Version 2.7.9 命令并将其粘贴到 VS 的 NuGet 控制台中。 它将安装支持包。

第 5 步:这是我用来运行存储在 Python.exe 目录中的 .py 文件的代码。

using IronPython.Hosting;//for DLHE
using Microsoft.Scripting.Hosting;//provides scripting abilities comparable to batch files
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Hi
{
private static void Main(string []args)
{
Process process = new Process(); //to make a process call
ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
engine.ExecuteFile(@"C:\Users\daulmalik\AppData\Local\Programs\Python\Python37\p1.py");//Path of my .py file that I would like to see running in console after running my .cs file from VS.//process.StandardInput.Flush();
process.StandardInput.Close();//to close
process.WaitForExit();//to hold the process i.e. cmd screen as output
}
} 

第 6 步:保存并执行代码

设置 WorkingDirectory 或在 Argument 中指定 python 脚本的完整路径

ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
//start.WorkingDirectory = @"D:\script";
start.Arguments = string.Format("D:\\script\\test.py -a {0} -b {1} ", "some param", "some other param");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
    using (StreamReader reader = process.StandardOutput)
    {
        string result = reader.ReadToEnd();
        Console.Write(result);
    }
}

我在使用stdin/stout时遇到问题 - 当有效负载大小超过几千字节时它会挂起。 我不仅需要使用一些短参数调用 Python 函数,还需要使用可能很大的自定义有效负载。

前阵子,我写了一个虚拟actor库,允许通过Redis在不同的机器上分配任务。 为了调用 Python 代码,我添加了用于侦听来自 Python 的消息、处理它们并将结果返回给 .NET 的功能。 下面是它如何工作的简要说明

它也适用于单台机器,但需要一个 Redis 实例。 Redis 增加了一些可靠性保证——有效载荷被存储,直到工作确认完成。 如果工作死亡,有效载荷将返回到作业队列,然后由另一个工作人员重新处理。

有同样的问题,这对我有用:

using IronPython.Hosting;

  var engine = Python.CreateEngine();

  engine.ExecuteFile("") //put the directory of the program in the quote marks
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);
         }
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM