wxpython

Tim Golden mail at timgolden.me.uk
Wed Jan 23 06:49:58 EST 2008


joe jacob wrote:
> I am trying to open a file containing non displayable characters like
> contents an exe file. The is is with the below mentioned code:
> 
> self.text_ctrl_1.SetValue(file_content)
> 
> If the file_content contains non displayable characters I am getting
> an error like this:
> 
> Traceback (most recent call last):
>   File "C:\Documents and Settings\joe_jacob\Desktop\notepad.py", line
> 102, in open_file
>     self.text_ctrl_1.SetValue(file_content)
>   File "D:\softwares\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx
> \_controls.py", line 1708, in SetValue
>     return _controls_.TextCtrl_SetValue(*args, **kwargs)
>   File "D:\softwares\Python25\lib\encodings\cp1252.py", line 15, in
> decode
>     return codecs.charmap_decode(input,errors,decoding_table)
> UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position
> 2: character maps to <undefined>
> 
> I am trying to create an encryption program so if I open any file even
> if it is an exe file it should display in text ctrl.
> 
> What is this problem with this ? How can I rectify this?

If I may be permitted a bit of levity at your expense: you're asking
how to display "non displayable" characters! The most serious answer
I can give is: how do you *want* to display those characters? What
do you *expect* to appear in the text control.

wxPython is trying to interpret your byte stream as a Unicode
text stream encoded as cp1252. But it's not, so it gives up
in a heap. One solution is to pass the repr of file_content.
Another solution is for you to prefilter the text, replacing 
non-printables by their hex value or by some marker. Not much
in it, really.

<code>
import random
file_content = "".join (
   chr (random.randint (0, 255)) for i in range (1000)
)
munged_text = "".join (
   c if 32 <= ord (c) <= 126 else hex (ord (c)) for c in file_content
)

print repr (file_content)
print munged_text
</code>

TJG



More information about the Python-list mailing list