[IronPython] how to change default encoding of string and file at runtime?

Dino Viehland dinov at exchange.microsoft.com
Wed Dec 28 01:57:32 CET 2005


This is an interesting issue...  If I take your same code and run it on CPython it raises an exception:

a= u'\u6211\u4eec'
f = open('1.txt', 'w')
f.write(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

(the print also raises on CPython, but I'm ignoring that for now :) )

But changing this to use the default encoding would probably break some compatibility w/ CPython.

One immediate work around is to use the .NET file classes directly where you can supply the encoding yourself - but that would be more cumbersome then having some native support here.  This one deserves some thought around getting the right solution.  


-----Original Message-----
From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of opin2 hu
Sent: Saturday, December 24, 2005 11:03 PM
To: users at lists.ironpython.com
Subject: [IronPython] how to change default encoding of string and file at runtime?

I run IronPython0.9.6 in Win2000, System Default encoding is GBK( 
simplified Chinese ) 
in IronPythonConsole: 

>>>a= u'\u6211\u4eec' 
>>>print a
>>>f = open("1.txt", "w") 
>>>f.write( a ) 
>>>f.close() 

open the file, only "??" in 1.txt 


I grep "Encoding.ASCII" in source files, 
then replace "Encoding.ASCII" with "Encoding.Default": 

AST/Parser.cs line 44 System.Text.Encoding.ASCII -> 
System.Text.Encoding.Default 

Objects/PythonFile.cs line 202 Encoding.ASCII -> Encoding.Default 

Objects/BaseStr.cs line 108 Encoding.ASCII -> Encoding.Default 

Objects/BaseStr.cs line 188 Encoding.ASCII -> Encoding.Default 

rebuild Ironpython,  redo above test, everything works fine. 

I don't know whether it is a right way to solve the problem? 
how to change default encoding of string and file  at runtime

_________________________________________________________________
与联机的朋友进行交流,请使用 MSN Messenger:  http://messenger.msn.com/cn  




More information about the Ironpython-users mailing list