3

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
            }
        }
Ropstah
  • 17,538
  • 24
  • 120
  • 194
  • 2
    If there is a way (IPC?) to communicate between c# and python, then you can run python program once and keep it opened. Python will simply wait until c# ask for something to do, process it and will continue waiting. – Sinatr Feb 04 '15 at 13:49
  • Ah "http://stackoverflow.com/questions/23374854/simplest-way-to-communicate-between-python-and-c-sharp-using-ipc". I was looking at it from a wrong perspective – Ropstah Feb 04 '15 at 14:13

1 Answers1

1

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.

  • I think this might actually be what I need – Ropstah Feb 13 '15 at 13:56
  • I was following this tutorial: https://ernest-bonat.medium.com/using-c-to-call-python-restful-api-web-services-with-machine-learning-models-6d1af4b7787e but the httpWebRequest.GetResponse() takes long. Is there a faster solution? – augre Jun 03 '21 at 11:43