如何从C#运行Python脚本?

Inb*_*ose 111 .net c# python ironpython python.net

之前已经在不同程度上提出了这类问题,但我觉得它没有以简洁的方式回答,所以我再次提出这个问题.

我想用Python运行一个脚本.让我们说是这样的:

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

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

好的,那我怎么在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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我通过code.py位置cmdfilename位置,因为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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mas*_*ity 105

它不工作的原因是因为你有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);
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

  • @MasterMorality,python脚本执行得很好,但是如果python中有一些模块依赖,我们如何解决这个问题? (5认同)
  • 如果 Python 安装程序被告知将 Python 目录添加到环境变量 PATH(特定于系统或用户),则无需提供路径即可工作。 (2认同)

Chr*_*way 55

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

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

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

在这里获取IronPython.

  • 请注意,IronPython和Python并不完全相同.仅供记录...... (7认同)
  • 向我解释一下,我可以这样做而不必下载任何东西吗?c#准备好了这个插件吗?还 - 我可以用这个运行外部脚本吗? (3认同)
  • IronPython 似乎不支持与 Python 3.6.x 相同的一组语言功能。因此,如果您不使用任何这些语言功能,则 IronPython 只是一个选项。不过,这绝对值得一试。 (3认同)
  • 我们可以用ironpython 2.7版本运行python 3.6吗?我尝试过,但它没有导入任何 python 库。我收到“意外的令牌”,请帮忙 (2认同)

Roh*_*nke 26

从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();

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Python sample_script

print "Python C# Test"

您将在C#的控制台中看到"Python C#Test".


Der*_*rek 12

我遇到了同样的问题,Master Morality的回答并没有为我做.以下是基于之前的答案,有效:

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);
     }
 }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 有人可以评论为什么这是-1。它出什么问题了。 (2认同)
  • 它与上面的答案完全相同,只是从参数中分配FileName.但最后`start`具有相同的值 (2认同)

cs0*_*815 6

也请您注意:

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

效果很好。

  • 此链接现在重定向到主题列表。只有一篇提到了 Python,而且相关性不大。 (7认同)

小智 5

实际上,使用 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
}
} 
Run Code Online (Sandbox Code Playgroud)

第6步:保存并执行代码

  • 作为一名开发人员,我不会因为它“容易”实现而选择解决方案。我选择一个能完成这项工作的人。IronPython 仅移植到 python 2.7,而 python 3 的工作已经进行了几年,而且还没有结束的迹象。希望你的 python 代码是正确的版本。 (3认同)