[IronPython] Redirecting stdout/stderr, but with context

Dino Viehland dinov at microsoft.com
Sat Jan 31 03:45:01 CET 2009

Can you run each document on its own thread?

Oh, it also looks like we actually flow CodeContext through to the caller.  So you could do something like:

class MyFile {
        public void write(CodeContext context, string data) {
                Scope curScope = context.Scope;         // this gives you the module you're running in

                // handle write here keyed off of the scope object

And replace sys.stdout with that.

-----Original Message-----
From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Jeff Slutter
Sent: Friday, January 30, 2009 6:41 PM
To: Discussion of IronPython
Subject: Re: [IronPython] Redirecting stdout/stderr, but with context

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 )
  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).

Users mailing list
Users at lists.ironpython.com

More information about the Ironpython-users mailing list