1

this question could seem as duplicate, i have tried all the suggested solution but in vain , i wanna redirect python script output using this code :

    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo.FileName = "python.exe";
    proc.StartInfo.Arguments = Application.StartupPath.Replace("\\bin\\Debug", "") + "\\scripts\\test.py";
    proc.OutputDataReceived += OutputDataReceived;
    proc.ErrorDataReceived += ErrorDataReceived;

    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 

    proc.Start();
    //proc.WaitForExit();

    StringBuilder q = new StringBuilder();
    while (!proc.HasExited)
    {
        q.Append(proc.StandardOutput.ReadToEnd());
    }
    string r = q.ToString();
    r = proc.StandardOutput.ReadToEnd();
    MessageBox.Show(r);
}
private void OutputDataReceived(object sender, DataReceivedEventArgs args)
{
    //textOutput.Text += args.Data;
    MessageBox.Show(args.Data);
}

the python script contains print "hello test" i tried unbuffering output but vainly.

Any help please.

I'm using VS 2010 .NET 4.0 , Python 2.7 , winXP sp3.

1 Answer 1

3

Try to create a StreamReader instance instead of StringBuilder. this code works for me just fine:

 System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = "ping.exe";
        proc.StartInfo.Arguments = "8.8.8.8";


        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

        proc.Start();
       StreamReader q = proc.StandardOutput;
       while (!proc.HasExited)
         Console.WriteLine(q.ReadLine());

        Console.ReadKey();
Sign up to request clarification or add additional context in comments.

3 Comments

and if that doesn't work you could always use the pipe operator to write to a file and read that one
it hadn't worked, but i need to have the redirected output in realtime
I added code, it works for me and it prints line by line (maybe not best way to do it, I never learned C#)

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.