0

i want to create IDE for python that can run line by line like anaconda. so i want return the output after each python command .

Edit: the solution is:

public Process cmd = new Process();
public  string output = "";
{
cmd.StartInfo.FileName = "python.exe";
cmd.StartInfo.Arguments = @"-i";//this was the problem
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.UseShellExecute = false;

cmd.OutputDataReceived += new DataReceivedEventHandler((sender2, e2) =>
{
    if (!String.IsNullOrEmpty(e2.Data))
    {
        output += e2.Data.ToString()+"\n";

    }
});
cmd.Start();
cmd.BeginOutputReadLine();
}

{
cmd.StandardInput.WriteLine(result);//the output will take some time to complete
}
Osama Adel
  • 176
  • 1
  • 10

1 Answers1

-1

register to the OutputDataReceived event to get data :

    cmd.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
    {
        if (!String.IsNullOrEmpty(e.Data))
        {
            // do what you need with the output (for instance append output)
        }
    });

and after cmd.Start() add:

   cmd.BeginOutputReadLine();

this causes the process to read the redirected output..

so the final code would be:

        Process cmd = new Process();
        cmd.StartInfo.FileName = @"python.exe";
        cmd.StartInfo.Arguments = @"-i";
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.StartInfo.RedirectStandardInput = true;
        cmd.StartInfo.UseShellExecute = false;
        cmd.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
        {
            if (!String.IsNullOrEmpty(e.Data))
            {
                // do what you need with the output (for instance append output)
                cmd.StandardInput.WriteLine("python comand 1");
                cmd.StandardInput.WriteLine("python comand 2");
                cmd.StandardInput.WriteLine("another comand 3");

            }
        });
        cmd.Start();
        cmd.BeginOutputReadLine();

the exe I'm running basically has a button that on click writes a line to the console, and then reads 3 lines, so the event gets data "my output", and bla1,bla2 and bla3 get the values I wrote to the input:

    private void button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine("my output");
        string bla = Console.ReadLine();
        string bla2 = Console.ReadLine();
        string bla3 = Console.ReadLine();
    }
audzzy
  • 721
  • 1
  • 4
  • 12