y306237357 2015-10-13 08:47 采纳率: 0%
浏览 1747

如何在WPF上获取 python 编译器的控制台输出信息

详细代码如下,求大神们指导一下,如何获取python 的控制台输出内容。我使用的是Pyehon3.43,开发环境vs2012 + win7

 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using IronPython.Hosting;

namespace WpfApplication2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            string[] strArr = new string[5];//参数列表
            string sArguments = @"Hello.py";//这里是python的文件名字
            //RunPythonScript(sArguments, "-u", strArr);
            RunPythonScript(sArguments, "-u", strArr);
        }


        public void RunPythonScript(string sArgName, string args = "", params string[] teps) 
        {
            Process p = new Process();
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + sArgName;// 获得python文件的绝对路径     
            p.StartInfo.FileName = @"D:\Program Files (x86)\Pyehon3.43\python.exe";

            string sArguments = "\"" + path + "\"";
            if (teps.Length > 0)
            {
                foreach (string sigstr in teps)
                {
                    if (!string.IsNullOrEmpty(sigstr))
                    {
                        sArguments += " " + sigstr;//传递参数
                    }      
                }
            }
            if (args.Length > 0)
            {
                sArguments += " " + args;
            }

            p.StartInfo.Arguments = sArguments;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;

            p.Start();
            p.BeginOutputReadLine();
            p.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            Console.ReadLine();
            p.WaitForExit();
        }

        private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                this.AppendText(e.Data + Environment.NewLine);
            }
        }
        public delegate void AppendTextCallback(string text);

        public void AppendText(string text)
        {
            Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.SystemIdle,
                new Action(() =>
                {
                    this.TextBox.AppendText(text);
                }));
        }  
    }
}

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-04 11:45
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    要从Windows Presentation Foundation(WPF)应用程序中获取Python编译器的控制台输出信息,你可以创建一个自定义事件处理程序来捕获并显示输出。以下是一个示例:

    public class PythonProcessOutputHandler : IHostedService
    {
        private readonly IProcess _process;
    
        public PythonProcessOutputHandler(IProcess process)
        {
            _process = process;
        }
    
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _process.Start();
    
            return Task.CompletedTask;
        }
    
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _process.KillAsync().ConfigureAwait(false);
        }
    }
    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var host = new PythonHost();
            var pythonProcess = host.GetPythonProcess();
    
            pythonProcess.OutputDataReceived += OnOutputDataReceived;
            pythonProcess.ErrorDataReceived += OnErrorDataReceived;
        }
    
        private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            TextBox.AppendText(e.Data);
        }
    
        private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            TextBox.AppendText($"Error: {e.Data}");
        }
    }
    

    在这个示例中,我们首先创建了一个名为PythonProcessOutputHandler的类,它继承自IHostedService接口,并重写了其两个方法:StartAsyncStopAsync。然后,在MainWindow类中,我们初始化了Python服务实例,并将OutputDataReceivedErrorDataReceived事件处理器添加到Python进程。

    当Python进程开始运行时,我们通过调用OnOutputDataReceivedOnErrorDataReceived方法来监听输出和错误消息。这些方法会将接收到的数据添加到文本框中。

    注意,这只是一个基本示例,实际应用可能需要根据你的具体需求进行修改。例如,你可能需要更详细的错误处理,或者在控制台输出中添加额外的信息等。

    评论

报告相同问题?