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
            }
        }
2
  • 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. Commented Feb 4, 2015 at 13:49
  • Ah "stackoverflow.com/questions/23374854/…". I was looking at it from a wrong perspective Commented Feb 4, 2015 at 14:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think this might actually be what I need
I was following this tutorial: ernest-bonat.medium.com/… but the httpWebRequest.GetResponse() takes long. Is there a faster solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.