[IronPython] Redirecting stdout/stderr, but with context

Jeff Slutter jslutter at reactorzero.com
Sat Jan 31 03:41:28 CET 2009


Dino Viehland wrote:
> You can always provide your own stream which is aware of what the current output window is.  It could store this in a thread static or just some variable that you update whenever the active window changes.  You can set that via ScriptRuntime.IO.OutputStream.  You could conceptually do the exact same thing from Python just by setting sys.stdout to a file-like object which knows what the current output window is.

This is what I'm doing right now and that's where I'm having my problem.
   I don't think this is a solvable problem since the output stream is
shared by all ScriptScopes, just as the output stream for
System.Console.WriteLine is the same across the process.

In a nutshell, I have this:

class Document
{
  void AppendOutput( string text )
  {
    m_buffer.Add(text);
  }
  List<string> m_buffer;
}

class ConsoleWindow: Form
{
   public void WriteOutput( string text, Document doc )
   {
      doc.AppendOutput( text );
      if( doc == m_currentDisplayingDoc )
      {
         textBox.Text += text;
      }
   }
}

class DocWriter
{
  public DocWriter( ConsoleWindow console, Document doc )
  {
    m_console = console;
    m_document = doc;
  }

  public void write(string text)
  {
    m_console.WriteOutput( text, m_document );
  }
  ConsoleWindow m_console;
  Document m_document;
}

void OnDocumentActivate(Document doc)
{
  DocWriter writer = new DocWrite(guiConsole, doc);
  object sysObj = doc.scope.GetVariable("sys");
  m_engine.Operations.SetMember(sysObj, "stdout", writer);
  m_engine.Operations.SetMember(sysObj, "stderr", writer);
}


The problem is:
If there is a script running on DocumentA, that is streaming output, and
then I switch to DocumentB while DocumentA continues to run - the output
for DocumentA starts appearing in the console window for DocumentB as if
it was for B. This is because sysout is system wide and if I change it
while DocumentA is writing, then it starts outputting to the new stream
that was set (and that was registered with DocumentB).


-Jeff



More information about the Ironpython-users mailing list