0

As a school project my class made a simple programing language in python 3. Now we made a simple ide in c# that should execute python script in a new console window. I was wondering what is most efficient way to do it. (I should execute it with parameters)

2
  • what did you try so far? please post your code Commented May 14, 2015 at 10:29
  • I tried to use IronPython and with ProcessStartInfo but IronPython was not working every time i tried and ProcessStartInfo would close automatically. Here's my project mediafire.com/?81ppkgl5fpel595 Commented May 14, 2015 at 11:35

2 Answers 2

1

You can use ProcessStartInfo

int parameter1 = 10;
int parameter2  = 5
Process p = new Process(); // create process to run the python program
p.StartInfo.FileName = "python.exe"; //Python.exe location
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false; // ensures you can read stdout
p.StartInfo.Arguments = "c:\\src\\yourpythonscript.py "+parameter1 +" "+parameter2; // start the python program with two parameters
p.Start(); // start the process (the python program)
StreamReader s = p.StandardOutput;
String output = s.ReadToEnd();
Console.WriteLine(output);
p.WaitForExit();
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this and consloe opens and closes without any output
I won't be able to access that until later today, but I have corrected the script so it doesn't parse the output. It works correctly for a print "Hello World" app.
0

There is two way to run the python script:

  1. One way is to run the python script is by running the python.exe file:
    Run the python.exe file using ProcessStartInfo and pass the python script on it.

private void run_cmd(string cmd, string args) {
ProcessStartInfo start = new ProcessStartInfo();

     start.FileName = "my/full/path/to/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);
         }
     }  
}
  1. Another way is using IronPython and execute the python script file directly.

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Comments

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.