【问题标题】:Python console in C#C# 中的 Python 控制台
【发布时间】:2013-03-01 10:34:32
【问题描述】:

我正在尝试创建一个实现 python 控制台的控件。不幸的是,它没有收到任何 Python 输出。

    Queue<string> qstring = new Queue<string>();
    Thread thread;
    Process prc;
    void pythonmain()
    {
        if (DesignMode) return;
        prc = new Process();
        prc.StartInfo.FileName = "python";
        prc.StartInfo.Arguments = " -u";
        prc.StartInfo.RedirectStandardInput = true;
        prc.StartInfo.RedirectStandardOutput = true;
        prc.StartInfo.RedirectStandardError = true;
        prc.StartInfo.UseShellExecute = false;
        prc.StartInfo.CreateNoWindow = true;

        prc.EnableRaisingEvents = true;
        prc.OutputDataReceived += new DataReceivedEventHandler(prc_OutputDataReceived);
        prc.ErrorDataReceived += new DataReceivedEventHandler(prc_ErrorDataReceived);
        prc.SynchronizingObject = this;

        prc.Start();
        prc.BeginOutputReadLine();
        prc.BeginErrorReadLine();




        while (!prc.HasExited)
        {
            lock (qstring)
            {
                if (qstring.Count > 0) prc.StandardInput.Write(qstring.Dequeue()+"\n");
            }
        }


        prc.WaitForExit();
    }

    void prc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (e.Data != null)
        {
            richTextBox1.BeginInvoke(new Action<string>((s) => richTextBox1.AppendText(s)),e.Data);
        }
    }

    void prc_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        System.Diagnostics.Process p = (Process)sender;

        if (e.Data != null)
        {
            richTextBox1.BeginInvoke(new Action<string>((s) => richTextBox1.AppendText(s)), e.Data);
        }
    }


    public PyConsoleControl()
    {
        InitializeComponent();
        if (!DesignMode)
        {
        thread = new Thread(pythonmain);
        thread.IsBackground = true;
        thread.Start();
        }
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            lock (qstring)
            {
                qstring.Enqueue(textBox1.Text);
            }
            textBox1.Clear();
        }
    }
}

您如何看到我正在创建一个正在启动 Python shell 的新线程,但没有返回 Python 输出。我该如何解决?

【问题讨论】:

标签: c# python multithreading process


【解决方案1】:

一定要看看IronPython,它几乎肯定会为所欲为。

例如

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
// we get access to Action and Func on .Net 2.0
using Microsoft.Scripting.Utils;

namespace TestCallIronPython
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            ScriptEngine pyEngine = Python.CreateEngine();
            ScriptScope pyScope = pyEngine.CreateScope();
            pyScope.SetVariable("test", "test me");

            string code = @"
             print 'test = ' + test
             class MyClass:
             def __init__(self):
               pass

             def somemethod(self):
               print 'in some method'

             def isodd(self, n):
               return 1 == n&nbsp;% 2
           ";
           ScriptSource source = pyEngine.CreateScriptSourceFromString(code);
           CompiledCode compiled = source.Compile();
           compiled.Execute(pyScope);

           // Get the Python Class
           object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass"));
           // Invoke a method of the class
           pyEngine.Operations.InvokeMember(MyClass, "somemethod", new object[0]);

           // create a callable function to 'somemethod'
           Action SomeMethod2 = pyEngine.Operations.GetMember&lt;Action&gt;(MyClass, "somemethod");
           SomeMethod2();

           // create a callable function to 'isodd'
           Func&lt;int, bool&gt; IsOdd = pyEngine.Operations.GetMember&lt;Func&lt;int, bool&gt;&gt;(MyClass, "isodd");
           Console.WriteLine(IsOdd(1).ToString());
           Console.WriteLine(IsOdd(2).ToString());

           Console.Write("Press any key to continue . . . ");
           Console.ReadKey(true);
       }
   }
}

直接取自this示例。

【讨论】:

    【解决方案2】:

    请注意,您应该确保该进程实际启动,为此您应该检查方法启动的结果。如果进程启动则返回 true,否则返回 false。

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多