Problem With Embedded Icon and Python 3.4

Zachary Ware zachary.ware+pylist at gmail.com
Fri Mar 25 01:34:13 EDT 2016


On Fri, Mar 25, 2016 at 12:10 AM, Wildman via Python-list
<python-list at python.org> wrote:
> I have a program that I have been trying to rewrite so it will
> run on Python 2.7 and 3.4.  It has been a pain to say the least.
> Thank $DIETY for aliases.  Anyway, I got it all working except
> for one thing.  The program has an embedded icon.  It is displayed
> in the window's titlebar.  The icon is a 16x16 png that has been
> base64 encoded using a Linux utility called memencoder.  The code
> below works perfectly with Python 2.7.  The icon data is complete
> for anyone that wants to try to run this code:
>
> encoded_icon = """\
[...]
> I tried converting the icon string to a byte variable like this:
>
> encoded_icon = bytes("""\
> iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBj
>     (...)
> ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""")
>
>
> That give me a different error:
>
> Traceback (most recent call last):
>   File "./myprogram.py", line 269, in <module>
>     ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""")
> TypeError: string argument without an encoding
>
> I'm not sure what that means.  I looks like it wants the string
> to be encoded but it already is.

The bytes constructor in Python 3 requires you to provide an encoding
(utf-8, ascii, latin-1, koi8, etc) when passing in a string, otherwise
it doesn't know what bytes you want and refuses to guess.  You could
fix this by adding `encoding='ascii'` to the bytes() call–but I'm not
certain that that would work in 2.7, and there's a much easier method,
noted later.

> And why the reference to only
> the last line of the string?

Because the traceback would be huge if it included the entire function
call, and there's no need to.  You can find the error from just that
line.  It would be arguably more useful to show the first line, but
that's more difficult to do.

> I am at a loss here.  Any help would be greatly appreciated.

What you need here is a bytes literal, which is accomplished by
prepending a 'b' to the string literal.   Your `encoded_icon = """\`
just needs to become `encoded_icon = b"""\`.  See here [1] for more
information.

-- 
Zach

[1] https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals



More information about the Python-list mailing list