Python script output redirection using C#

我只是一个虾纸丫 提交于 2019-12-23 04:52:44

问题


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:


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();


来源:https://stackoverflow.com/questions/13671733/python-script-output-redirection-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!