详细代码如下,求大神们指导一下,如何获取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);
}));
}
}
}