2010-02-03 55 views
0

我建立一个IronPython的发动机或多或少像这样:如何关闭执行脚本的IronPython引擎的输入流?

var engine = IronPython.Hosting.Python.CreateEngine();     
var scope = engine.CreateScope(); 

// my implementation of System.IO.Stream 
var stream = new ScriptOutputStream(engine); 
engine.Runtime.IO.SetOutput(stream, Encoding.UTF8); 
engine.Runtime.IO.SetErrorOutput(stream, Encoding.UTF8); 
engine.Runtime.IO.SetInput(stream, Encoding.UTF8); 

var script = engine.CreateScriptSourceFromString(source, SourceCodeKind.Statements); 
script.Execute(scope); 

可变source是具有下列内容(Python语句)的字符串:

import code 
code.interact(None, None, 
     { 
      '__name__' : '__console__', 
      '__doc__' : None, 
     }) 

的流正被托管在一个窗口形成。当这个表格关闭时,我希望口译员退出。显然,我试图在Read方法关闭流:

/// <summary> 
    /// Read from the _inputBuffer, block until a new line has been entered... 
    /// </summary> 
    public override int Read(byte[] buffer, int offset, int count) 
    { 

     if (_gui.IsDisposed) 
     { 
      return 0; // msdn says this indicates the stream is closed 
     } 

     while (_completedLines.Count < 1) 
     { 
      // wait for user to complete a line 
      Application.DoEvents(); 
      Thread.Sleep(10); 
     } 
     var line = _completedLines.Dequeue(); 
     return line.Read(buffer, offset, count); 
    } 

成员变量_completedLines保持表示用户已输入线MemoryStream对象的队列。 _gui是对windows窗体的引用 - 当它被丢弃时,我不知何故希望IronPython引擎停止执行code.interact()。 (Read只是再次调用)。提高一个例外从documentation of Read无法正常工作或:它停止解释的执行,但在Read方法:(

我自己也尝试返回^Z(0X1A)和^D(0×04)内的IDE中断Read的缓冲区,因为这些在控制台上用于退出解释器,但这根本不起作用...

回答

1

我花了一秒钟的时间来弄清楚你想要什么,但这看起来像一个在IronPython中的错误code.interact预计EOFError会从raw_input内建中产生,表示该循环结束的时间,但IronPython不会这么做 - 它只是返回一个em pty字符串。这是IronPython issue #22140

你可以尝试抛出一个EndOfStreamException,它会转换为EOFError。这可能足以欺骗它。

+0

我试过engine.Runtime.Shutdown() - 它不工作:(我会再试一次,虽然... – 2010-02-04 07:33:24

+0

我试着抛出SystemExitException - 这仍然会导致IDE在自定义流类中断开(未处理的用户异常),即使script.Excecute()*的调用者*处理错误... – 2010-02-04 10:09:09

+0

我重写了我的答案,以更好地解决您的问题 - 不确定这是您想要听到的答案,但 – 2010-02-04 16:22:19

相关问题