How can I redirect the stdout of IronPython in C#?

后端 未结 3 1721
情话喂你
情话喂你 2020-12-05 11:04

I have the following:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button3_Click(objec         


        
3条回答
  •  鱼传尺愫
    2020-12-05 12:03

    Your example is close to working.

    The problem you saw is because sys.stdout=my.write should be sys.stdout=my. It also appears that Python expects to find a boolean softspace attribute.

    I have made these two changes in the code below. Hopefully this should now work as you expected.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                var strExpression = @"
    import sys
    sys.stdout=my
    print 'ABC' ";
    
                var engine = Python.CreateEngine();
                var scope = engine.CreateScope();
                var sourceCode = engine.CreateScriptSourceFromString(strExpression);
                scope.SetVariable("my", this);
                var actual = sourceCode.Execute(scope);
                textBox1.Text += actual;
            } catch (System.Exception ex) {
                MessageBox.Show(ex.ToString());
            }
        }
    
        public bool softspace;
    
        public void write(string s)
        {
            textBox1.Text += s;
        }
    }
    

提交回复
热议问题