How do I run a Python script from C#?

后端 未结 8 1885
猫巷女王i
猫巷女王i 2020-11-22 02:47

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

8条回答
  •  情书的邮戳
    2020-11-22 03:20

    Actually its pretty easy to make integration between Csharp (VS) and Python with IronPython. It's not that much complex... As Chris Dunaway already said in answer section I started to build this inegration for my own project. N its pretty simple. Just follow these steps N you will get your results.

    step 1 : Open VS and create new empty ConsoleApp project.

    step 2 : Go to tools --> NuGet Package Manager --> Package Manager Console.

    step 3 : After this open this link in your browser and copy the NuGet Command. Link: https://www.nuget.org/packages/IronPython/2.7.9

    step 4 : After opening the above link copy the PM>Install-Package IronPython -Version 2.7.9 command and paste it in NuGet Console in VS. It will install the supportive packages.

    step 5 : This is my code that I have used to run a .py file stored in my Python.exe directory.

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

    step 6 : save and execute the code

提交回复
热议问题