[IronPython] Oddity with Setting Output Stream

Michael Foord fuzzyman at voidspace.org.uk
Fri Oct 31 15:35:08 CET 2008


Hello guys,

Another oddity with the IronPython 2 hosting API. This one may be the 
correct behaviour, but it is different from IronPython 1.

When we set a UTF8 output stream on a runtime we see a UTF8 BOM being 
written with the first output. I'm sure this didn't happen with 
IronPython 1 because I now have failing tests!

The following code that traps standard out using a custom stream prints:

out: u'\ufeff'
out: 'foobar'
out: '\r\n'
out: 'foobar'
out: '\r\n'

import sys
import clr
clr.AddReference('IronPython')
clr.AddReference('Microsoft.Scripting')

from IronPython.Hosting import Python
from Microsoft.Scripting import SourceCodeKind
from System.Text import Encoding
from System.IO import MemoryStream

class CustomStream(MemoryStream):
    def __new__(cls, prefix):
        return MemoryStream.__new__(cls)
       
    def __init__(self, prefix):
        self._prefix = prefix
       
    def Write(self, buffer, offset, count):
        print self._prefix,
        print repr(Encoding.UTF8.GetString(buffer, offset, count))

engine = Python.CreateEngine()
engine.Runtime.IO.SetOutput(CustomStream('out:'), Encoding.UTF8)

source = engine.CreateScriptSourceFromString('print "foobar"\r\n', 
SourceCodeKind.Statements)
scope = engine.CreateScope()
code = source.Compile()

code.Execute(scope)
code.Execute(scope)

All the best,

Michael Foord

-- 
http://www.ironpythoninaction.com/




More information about the Ironpython-users mailing list