run a python script in csharp

To run a Python script in C#, you can use the Process class to execute a command-line process that runs the Python interpreter and passes your Python script as an argument.

Here's an example code snippet that demonstrates how to run a Python script from C#:

main.cs
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // the path to the Python interpreter executable
        string python = @"C:\Python39\python.exe";

        // the Python script to run
        string script = @"C:\path\to\your\python\script.py";
        
        // set up the process start info
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = python,
            Arguments = script,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        };

        // create the process and start it
        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();

        // read any output from the process
        string output = process.StandardOutput.ReadToEnd();

        // print the output
        Console.WriteLine(output);
    }
}
937 chars
36 lines

In this example, we first define the path to the Python interpreter executable and the path to the Python script to run. We then set up a ProcessStartInfo object with the appropriate command-line arguments to run the Python interpreter and pass the script as an argument. We create a Process object with this start info, and call its Start() method to start the process. We then read any output from the process and print it to the console.

gistlibby LogSnag