How do I run a Python script from C#?

后端 未结 8 1759
猫巷女王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#.

提交回复
热议问题