Comment 17 for bug 340394

Revision history for this message
Alexander Belchenko (bialix) wrote : Re: [Bug 340394] Re: want an option to set the output encoding, especially on win32

Tim пишет:
> http://bazaar-vcs.org/Integrating_with_Bazaar got me started.
>
> 1 : import bzrlib
> 2 : from bzrlib import log
> 6 : from bzrlib.branch import Branch
> 7 : b = Branch.open('./myscripts/')
> 11: import sys
> 12: lf = log.LongLogFormatter(to_file=sys.stdout)
> 14: log.show_log(b, lf)
>
> But it doesn't seem that simple:
...
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 9: ordinal not in range(128)
>
> What is wrong?
> Please give some advice.

sys.stdout is not what you want. You want to avoid creating temp file?
Then it's better to dump log into memory. You can't dump pure unicode to
stdout, do you? What about utf-8 instead? Ok?

So let's use StringIO Python standard library.

import codecs
from cStringIO import StringIO
import sys

import bzrlib
from bzrlib import log
from bzrlib.branch import Branch

# prepare utf-8 encoded stream
sio = codec.getwriter('utf-8')(StringIO())

# open branch
b = Branch.open('./myscripts/')

# print log to our stream
lf = log.LongLogFormatter(to_file=sio)
log.show_log(b, lf)

# get the log as utf-8 string
s = sio.getvalue()

# and then we can close our stream
sio.close()

Then you can use utf-8 data in s as you wish. You can print it to stdout:

sys.stdout.write(s)

or do something else.

HTH