How do I run a Python script from C#?

后端 未结 8 1739
猫巷女王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:02

    Execute Python script from C

    Create a C# project and write the following code.

    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"

    You will see the 'Python C# Test' in the console of C#.

    0 讨论(0)
  • If you're willing to use IronPython, you can execute scripts directly in C#:

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

    Get IronPython here.

    0 讨论(0)
  • 2020-11-22 03:16

    I ran into the same problem and Master Morality's answer didn't do it for me. The following, which is based on the previous answer, worked:

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

    As an example, cmd would be @C:/Python26/python.exe and args would be C://Python26//test.py 100 if you wanted to execute test.py with cmd line argument 100. Note that the path the .py file does not have the @ symbol.

    0 讨论(0)
  • 2020-11-22 03:16

    I am having problems with stdin/stout - when payload size exceeds several kilobytes it hangs. I need to call Python functions not only with some short arguments, but with a custom payload that could be big.

    A while ago, I wrote a virtual actor library that allows to distribute task on different machines via Redis. To call Python code, I added functionality to listen for messages from Python, process them and return results back to .NET. Here is a brief description of how it works.

    It works on a single machine as well, but requires a Redis instance. Redis adds some reliability guarantees - payload is stored until a worked acknowledges completion. If a worked dies, the payload is returned to a job queue and then is reprocessed by another worker.

    0 讨论(0)
  • 2020-11-22 03:17

    Just also to draw your attention to this:

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

    It works great.

    0 讨论(0)
  • 2020-11-22 03:17

    Set WorkingDirectory or specify the full path of the python script in the Argument

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题