我建立一個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
的緩衝區,因爲這些在控制檯上用於退出解釋器,但這根本不起作用...
我試過engine.Runtime.Shutdown() - 它不工作:(我會再試一次,雖然... – 2010-02-04 07:33:24
我試着拋出SystemExitException - 這仍然會導致IDE在自定義流類中斷開(未處理的用戶異常),即使script.Excecute()*的調用者*處理錯誤... – 2010-02-04 10:09:09
我重寫了我的答案,以更好地解決您的問題 - 不確定這是您想要聽到的答案,但 – 2010-02-04 16:22:19