Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C# execution of Python script be done faster by re-using process?

I'm executing a Python script from my C# console application. I made a bare solution which executes a script and solely prints a string to the output.

The Python initialization seems to take some time (about .5 second) which is quite annoying if i would like to run this code in some iterating code.

Is it possible to somehow re-use the created process so Python doesn't need to re-initialize? (p.s. IronPython is not an option due to missing libraries)

I'm using the following code to execute the script (this code runs in a for loop, 25 iterations takes about 10 seconds to run in total...):

        string cmd = @"Python/test.py";
        string args = "";
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"C:\ex\programs\Python27\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); //output works
            }
        }
like image 388
Ropstah Avatar asked Feb 24 '26 07:02

Ropstah


1 Answers

It is possible to create a restful service in python, that receives a command or a script as a string, and executes it (using exec).

This solution actually creates a remote python shell, which is much faster than creating a new process for every command.

This can also help you enable a stateful execution. In other words, any side effects your command causes, such as variable declaration, imports etc', will remain when you request more command executions from the server.

like image 200
Rafi Sasson Avatar answered Feb 26 '26 21:02

Rafi Sasson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!