2010-02-03 59 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

相關問題