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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With