f



UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

the following code originally from http://zetcode.com/databases/mysqlpythontutorial/
within the "Writing images" part .


import MySQLdb as mdb
import sys

try:
    fin = open("Chrome_Logo.svg.png",'rb')
    img = fin.read()
    fin.close()

except IOError as e:

    print ("Error %d: %s" % (e.args[0],e.args[1]))
    sys.exit(1)


try:
    conn = mdb.connect(host='localhost',user='testuser',
       passwd='test623', db='testdb')
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Images SET Data='%s'" % \
        mdb.escape_string(img))

    conn.commit()

    cursor.close()
    conn.close()

except mdb.Error as e:

    print ("Error %d: %s" % (e.args[0],e.args[1]))
    sys.exit(1)


I port it to python 3 ,and also change 
fin = open("chrome.png") 
to 
fin = open("Chrome_Logo.png",'rb')
but when I run it ,it gives the following error :

Traceback (most recent call last): 
  File "E:\Python\py32\itest4.py", line 20, in <module>
    mdb.escape_string(img))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

so how to fix it ?
0
iMath
12/6/2012 10:07:51 AM
comp.lang.python 77058 articles. 3 followers. Post Follow

4 Replies
2020 Views

Similar Articles

[PageSpeed] 19

On 12/6/2012 5:07 AM, iMath wrote:
> the following code originally from http://zetcode.com/databases/mysqlpythontutorial/
> within the "Writing images" part .
>
>
> import MySQLdb as mdb

Not part of stdlib. 'MySQLdb' should be in the subject line to get 
attention of someone who is familiar with it. I am not.

> import sys
>
> try:
>      fin = open("Chrome_Logo.svg.png",'rb')
>      img = fin.read()
>      fin.close()
>
> except IOError as e:
>
>      print ("Error %d: %s" % (e.args[0],e.args[1]))
>      sys.exit(1)
>
>
> try:
>      conn = mdb.connect(host='localhost',user='testuser',
>         passwd='test623', db='testdb')
>      cursor = conn.cursor()
>      cursor.execute("INSERT INTO Images SET Data='%s'" % \
>          mdb.escape_string(img))

 From the name, I would expect that excape_string expects text. From the 
error, it seems to specifically expect utf-8 encoded bytes. After 
decoding, I expect that it does some sort of 'escaping'. An image does 
not qualify as that sort of input. If escape_string takes an encoding 
arg, latin1 *might* work.

>      conn.commit()
>
>      cursor.close()
>      conn.close()
>
> except mdb.Error as e:
>
>      print ("Error %d: %s" % (e.args[0],e.args[1]))
>      sys.exit(1)
>
>
> I port it to python 3 ,and also change
> fin = open("chrome.png")
> to
> fin = open("Chrome_Logo.png",'rb')
> but when I run it ,it gives the following error :
>
> Traceback (most recent call last):
>    File "E:\Python\py32\itest4.py", line 20, in <module>
>      mdb.escape_string(img))
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
>
> so how to fix it ?
>


-- 
Terry Jan Reedy

0
tjreedy (5459)
12/6/2012 10:29:04 AM
On 6/12/12 11:07:51, iMath wrote:
> the following code originally from http://zetcode.com/databases/mysqlpythontutorial/
> within the "Writing images" part .
> 
> 
> import MySQLdb as mdb
> import sys
> 
> try:
>     fin = open("Chrome_Logo.svg.png",'rb')
>     img = fin.read()
>     fin.close()
> 
> except IOError as e:
> 
>     print ("Error %d: %s" % (e.args[0],e.args[1]))
>     sys.exit(1)
> 
> 
> try:
>     conn = mdb.connect(host='localhost',user='testuser',
>        passwd='test623', db='testdb')
>     cursor = conn.cursor()
>     cursor.execute("INSERT INTO Images SET Data='%s'" % \
>         mdb.escape_string(img))

You shouldn't call mdb.escape_string directly.  Instead, you
should put placeholders in your SQL statement and let MySQLdb
figure out how to properly escape whatever needs escaping.

Somewhat confusingly, placeholders are written as %s in MySQLdb.
They differ from strings in not being enclosed in quotes.
The other difference is that you'd provide two arguments to
cursor.execute; the second of these is a tuple; in this case
a tuple with only one element:

    cursor.execute("INSERT INTO Images SET Data=%s", (img,))

>     conn.commit()
> 
>     cursor.close()
>     conn.close()
> 
> except mdb.Error as e:
> 
>     print ("Error %d: %s" % (e.args[0],e.args[1]))
>     sys.exit(1)
> 
> 
> I port it to python 3 ,and also change 
> fin = open("chrome.png") 
> to 
> fin = open("Chrome_Logo.png",'rb')
> but when I run it ,it gives the following error :
> 
> Traceback (most recent call last): 
>   File "E:\Python\py32\itest4.py", line 20, in <module>
>     mdb.escape_string(img))
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
> 
> so how to fix it ?

Python 3 distinguishes between binary data and Unicode text.
Trying to apply string functions to images or other binary
data won't work.

Maybe correcting this bytes/strings confusion and porting
to Python 3 in one go is too large a transformation.  In
that case, your best bet would be to go back to Python 2
and fix all the bytes/string confusion there.  When you've
got it working again, you may be ready to port to Python 3.


Hope this helps,

-- HansM

0
hansmu (230)
12/6/2012 11:07:35 AM
On Thu, 06 Dec 2012 02:07:51 -0800, iMath wrote:

> the following code originally from
> http://zetcode.com/databases/mysqlpythontutorial/ within the "Writing
> images" part .
> 
> 
> import MySQLdb as mdb
> import sys
> 
> try:
>     fin = open("Chrome_Logo.svg.png",'rb') 
>     img = fin.read()
>     fin.close()
> except IOError as e:
>     print ("Error %d: %s" % (e.args[0],e.args[1]))
>     sys.exit(1)

Every time a programmer catches an exception, only to merely print a 
vague error message and then exit, God kills a kitten. Please don't do 
that.

If all you are going to do is print an error message and then exit, 
please don't bother. All you do is make debugging harder. When Python 
detects an error, by default it prints a full traceback, which gives you 
lots of information to track down the error. By catching that exception 
as you do, you lose that information and make it harder to debug.

Moving on to the next thing:


[snip code]
> I port it to python 3 ,and also change fin = open("chrome.png")
> to
> fin = open("Chrome_Logo.png",'rb')
> but when I run it ,it gives the following error :
> 
> Traceback (most recent call last):
>   File "E:\Python\py32\itest4.py", line 20, in <module>
>     mdb.escape_string(img))
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0:
> invalid start byte
> 
> so how to fix it ?

I suggest you start by reading the documentation for 
MySQLdb.escape_string. What does it do? What does it expect? A byte 
string or a unicode text string?

It seems very strange to me that you are reading a binary file, then 
passing it to something which appears to be expecting a string. It looks 
like what happens is that the PNG image starts with a 0x89 byte, and the 
escape_string function tries to decode those bytes into Unicode text:

py> img = b"\x89\x00\x23\xf2"  # fake PNG binary data
py> img.decode('utf-8')  # I'm expecting text
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: 
invalid start byte

Without knowing more about escape_string, I can only make a wild guess. 
Try this:

import base64
img = fin.read()  # read the binary data of the PNG file
data = base64.encodebytes(img)  # turn the binary image into text
cursor.execute("INSERT INTO Images SET Data='%s'" % \
        mdb.escape_string(data))


and see what that does.


-- 
Steven
0
12/6/2012 11:27:28 AM
=E5=9C=A8 2012=E5=B9=B412=E6=9C=886=E6=97=A5=E6=98=9F=E6=9C=9F=E5=9B=9BUTC+=
8=E4=B8=8B=E5=8D=887=E6=97=B607=E5=88=8635=E7=A7=92=EF=BC=8CHans Mulder=E5=
=86=99=E9=81=93=EF=BC=9A
> On 6/12/12 11:07:51, iMath wrote:
>=20
> > the following code originally from http://zetcode.com/databases/mysqlpy=
thontutorial/
>=20
> > within the "Writing images" part .
>=20
> >=20
>=20
> >=20
>=20
> > import MySQLdb as mdb
>=20
> > import sys
>=20
> >=20
>=20
> > try:
>=20
> >     fin =3D open("Chrome_Logo.svg.png",'rb')
>=20
> >     img =3D fin.read()
>=20
> >     fin.close()
>=20
> >=20
>=20
> > except IOError as e:
>=20
> >=20
>=20
> >     print ("Error %d: %s" % (e.args[0],e.args[1]))
>=20
> >     sys.exit(1)
>=20
> >=20
>=20
> >=20
>=20
> > try:
>=20
> >     conn =3D mdb.connect(host=3D'localhost',user=3D'testuser',
>=20
> >        passwd=3D'test623', db=3D'testdb')
>=20
> >     cursor =3D conn.cursor()
>=20
> >     cursor.execute("INSERT INTO Images SET Data=3D'%s'" % \
>=20
> >         mdb.escape_string(img))
>=20
>=20
>=20
> You shouldn't call mdb.escape_string directly.  Instead, you
>=20
> should put placeholders in your SQL statement and let MySQLdb
>=20
> figure out how to properly escape whatever needs escaping.
>=20
>=20
>=20
> Somewhat confusingly, placeholders are written as %s in MySQLdb.
>=20
> They differ from strings in not being enclosed in quotes.
>=20
> The other difference is that you'd provide two arguments to
>=20
> cursor.execute; the second of these is a tuple; in this case
>=20
> a tuple with only one element:
>=20
>=20
>=20
>     cursor.execute("INSERT INTO Images SET Data=3D%s", (img,))
>=20
>=20
thanks=EF=BC=8Cbut it still doesn't work
>=20
> >     conn.commit()
>=20
> >=20
>=20
> >     cursor.close()
>=20
> >     conn.close()
>=20
> >=20
>=20
> > except mdb.Error as e:
>=20
> >=20
>=20
> >     print ("Error %d: %s" % (e.args[0],e.args[1]))
>=20
> >     sys.exit(1)
>=20
> >=20
>=20
> >=20
>=20
> > I port it to python 3 ,and also change=20
>=20
> > fin =3D open("chrome.png")=20
>=20
> > to=20
>=20
> > fin =3D open("Chrome_Logo.png",'rb')
>=20
> > but when I run it ,it gives the following error :
>=20
> >=20
>=20
> > Traceback (most recent call last):=20
>=20
> >   File "E:\Python\py32\itest4.py", line 20, in <module>
>=20
> >     mdb.escape_string(img))
>=20
> > UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0:=
 invalid start byte
>=20
> >=20
>=20
> > so how to fix it ?
>=20
>=20
>=20
> Python 3 distinguishes between binary data and Unicode text.
>=20
> Trying to apply string functions to images or other binary
>=20
> data won't work.
>=20
>=20
>=20
> Maybe correcting this bytes/strings confusion and porting
>=20
> to Python 3 in one go is too large a transformation.  In
>=20
> that case, your best bet would be to go back to Python 2
>=20
> and fix all the bytes/string confusion there.  When you've
>=20
> got it working again, you may be ready to port to Python 3.
>=20
>=20
>=20
>=20
>=20
> Hope this helps,
>=20
>=20
>=20
> -- HansM

0
iMath
12/7/2012 3:42:47 PM
Reply:

Similar Artilces:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte
I just started to have this error without changing nothing in my index.html(template) and metrites.py(which ipen the template) [Thu Jul 04 11:35:14 2013] [error] [client 108.162.229.97] Original exception was: [Thu Jul 04 11:35:14 2013] [error] [client 108.162.229.97] Traceback (most recent call last): [Thu Jul 04 11:35:14 2013] [error] [client 108.162.229.97] File "/home/nikos/public_html/cgi-bin/metrites.py", line 19, in <module> [Thu Jul 04 11:35:14 2013] [error] [client 108.162.229.97] host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] or 'UnResolved' [Thu Jul 04 11:35:14 2013] [error] [client 108.162.229.97] UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte [Thu Jul 04 11:35:14 2013] [error] [client 108.162.229.97] Premature end of script headers: metrites.py Why cant it decode the starting byte? what starting byte is that? -- What is now proved was at first only imagined! Am 04.07.2013 10:37, schrieb Νίκος: > I just started to have this error without changing nothing Well, undo the nothing that you didn't change. ;) > UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: > invalid start byte > [Thu Jul 04 11:35:14 2013] [error] [client 108.162.229.97] Premature end > of script headers: metrites.py > > Why cant it decode the starting byte? what starting byte is that? It...

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte #2
Hello although my code is correct just today i saw this in the error_log [Sun Sep 29 07:44:43 2013] [error] [client 173.245.49.126] Traceback (most recent call last): [Sun Sep 29 07:44:43 2013] [error] [client 173.245.49.126] File "/home/nikos/public_html/cgi-bin/metrites.py", line 30, in <module> [Sun Sep 29 07:44:43 2013] [error] [client 173.245.49.126] host = socket.gethostbyaddr( ipval ) [0] [Sun Sep 29 07:44:43 2013] [error] [client 173.245.49.126] UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte [Sun Sep 29 07:44:43 2013] [error] [client 173.245.49.126] Premature end of script headers: metrites.py Which should never had happened since i use the following code: ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or os.environ.get('REMOTE_ADDR', "Cannot Resolve") ) city = "Άγνωστη Πόλη" host = "Άγνωστη Προέλευση" try: gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat') city = gi.time_zone_by_addr( ipval ) host = socket.gethostbyaddr( ipval ) [0] except socket.gaierror as e: print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ), file=open('/tmp/err.out', 'w') ) So vene if somethign might have gone wrong with the 'host' assignment, 'host' should have defaulted to "Άγνωστη Προέλευση" why the utf-8 error? Στις 29/9/2013 10:49 πμ...

[pysqlite 2.0.2] UnicodeDecodeError: 'utf8' codec can't decode bytes in position 44-45: invalid data
A fetchall() call causes the above error. There must be some non-utf8 chars in the table in question and - indeed - there very likely are: The table contains pathnames of files on the harddisk of a German "speaking" PC. What I have already done to try to overcome this is: - Inserted "# coding: iso-8859-1" (w/o the quotes) in (hopefully) every file of my project - All strings I could find prefixed with "u" (w/o the quotes) - Changed plain calls to execute(q) into execute(unicode(q)) Alas, I am not sure if this all makes really sense, and, obviously it doesn't...

RE: UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
This is a multipart message in MIME format. --Boundary_(ID_oK5MBHtGHXoVbM6v7o3uQQ) Content-type: text/plain; charset=utf-8 Content-transfer-encoding: quoted-printable Hi Terry, Thanks for your comment. =20 >To better help us help you, what exact version of Python? I use Python 2.7.5 =20 >Please post plain text without html. Sorry, I will do it. =20 >Please post programs single spaced with just occasional blank lines. =20 File my_program.py =20 import wx.aui import paramiko import telnetlib from LinuxHostPage import * from WindowsHostPage import * from AIXHostPage import * Publisher =3D pub.Publisher() TIMEOUT =3D 3 =20 class MainWindow(wx.Frame): def __init__(self, parent, title): =20 self.os =3D '' self.connection =3D [] =20 wx.Frame.__init__(self, parent, title=3Dtitle) self.SetBackgroundColour('LightGray') =20 # A Statusbar in the bottom of the window self.CreateStatusBar()=20 self.SetStatusText("Please input credentials.") =20 # Publisher Publisher().subscribe(self.change_statusbar, 'change_statusbar') =20 # Input box self.input_panel =3D wx.Panel(self) self.host =3D wx.StaticText(self.input_panel, -1, 'Host') self.host_entry =3D wx.TextCtrl(self.input_...

UnicodeDecodeError: 'ascii' codec can't decodee byte 0xff in position 0: ordinal not in range(128)
This is a multipart message in MIME format. --Boundary_(ID_E/4IbDwDEnubOe6Ijgqz/A) Content-type: text/plain; charset=utf-8 Content-transfer-encoding: quoted-printable Hi all, =20 I use Python telnetlib on Windows 7 32 bit. Here is my code: =20 def telnet(self, host, os, username, password): connection =3D telnetlib.Telnet(host) connection.read_until('login: ') connection.write(username + '\r') connection.read_until('assword: ') connection.write(password + '\r') connection.read_until('>', timeout =3D TIMEOUT) return connection =20 I can run the program in Eclipse and telnet successfully to a Windows = host. =20 But when I export to .exe file: =20 from distutils.core import setup import py2exe =20 setup( options =3D { "py2exe":{ "packages": ['wx.lib.pubsub'], "dll_excludes": ["MSVCP90.dll", "HID.DLL", "w9xpopen.exe"], } }, console =3D [{'script': =E2=80=98my_program.py'}] ) =20 and run the programe, I encounter this error: =20 UnicodeDecodeError: 'ascii' codec can't decodee byte 0xff in position 0: = ordinal not in range(128) =20 at line: =20 connection.write(username + '\r') =20 I have debugged...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 10: ordinal not in range(128)
I have no idea what is causing this error, or how to fix it. The full error is: Traceback (most recent call last): File "D:\ScriptRuntime\PS\Automation\Handlers\SCMTestToolResourceToolsBAT.py", line 60, in Run PS.Automation.Utility.System.AppendSystemPath(args["PATH"], context) File "D:\ScriptRuntime\PS\Automation\Utility\System.py", line 55, in AppendSys temPath AppendPathVariable("PATH", appendtext, context) File "D:\ScriptRuntime\PS\Automation\Utility\System.py", line 37, in AppendPat hVariable if(ap == pp): UnicodeDecod...

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 308: character maps to <undefined>
For 'mimetypes' in the code given below, python is giving the following error. Kindly help. >>> import os >>> matches = [] >>> for (dirname, dirshere, fileshere) in os.walk(r'C:\Python34'): for filename in fileshere: if filename.endswith('.py'): pathname = os.path.join(dirname, filename) if 'mimetypes' in open(pathname).read(): matches.append(pathname) Traceback (most recent call last): File "<pyshell#165>", line 5, in <module> if 'mimetypes' in open(pathname).read()...

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 10442: character maps to <undefined>
Im reading a file. But there seems to be some encoding error. >>> f =3D open(filename) >>> data =3D f.read() Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> data =3D f.read() File "C:\Python30\lib\io.py", line 1724, in read decoder.decode(self.buffer.read(), final=3DTrue)) File "C:\Python30\lib\io.py", line 1295, in decode output =3D self.decoder.decode(input, final=3Dfinal) File "C:\Python30\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,se...

UnicodeDecodeError: 'ascii' codec can't decode byte
Hello It seems like I have Unicode data in a CSV file but Python is using a different code page, so isn't happy when I'm trying to read and put this data into an SQLite database with APSW: ======== sql = "INSERT INTO mytable (col1,col2) VALUES (?,?)" cursor.executemany(sql, records("test.tsv")) """ UnicodeDecodeError: 'ascii' codec can't decode byte 0xc9 in position 18: ordinal not in range(128) """ ======== What should I do so Python doesn't raise this error? Should I convert data in the CVS file, or is there some f...

[2.5.1] "UnicodeDecodeError: 'ascii' codec can't decode byte"?
Hello I'm getting this error while downloading and parsing web pages: ===== title = m.group(1) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 48: ordinal not in range(128) ===== From what I understand, it's because some strings are Unicode, and hence contain characters that are illegal in ASCII. Does someone know how to solve this error? Thank you. Gilles Ganault wrote: > I'm getting this error while downloading and parsing web pages: > > ===== > title = m.group(1) > UnicodeDecodeError: 'ascii' codec can't...

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
The script is very simple (abc.txt exists in ROOTDIR directory): import os import shutil ROOTDIR = 'C:\Users\zoran' file1 = os.path.join(ROOTDIR, 'abc.txt') file2 = os.path.join(ROOTDIR, 'def.txt') shutil.move(file1, file2) But it returns the following error: C:\Python34\python.exe C:/Users/bckslash_test.py File "C:/Users/bckslash_test.py", line 4 ROOTDIR = 'C:\Users' ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape Process ...

'ascii' codec can't encode character u'\xe4' in position 4: ordinal not in range(128)
Hello friends, I am using pyWPS + GRASS to generate the maps for the given request XML. As my requestxml contains scandinavian letters , i got the following error, " 'ascii' codec can't encode character u'\xe4' in position 4: ordinal not in range(128) " The Request xml also contains encoding specification like <?xml version="1.0" encoding="UTF-8" standalone="yes"?> Then i traced the pywps code and added the following line, inputXml = inputXml.encode("utf-8") But it gives the following error, 'module' object has no attribute 'parsers'. Whats the wrong in my code? Do any one implemented the pywps with scandinavian letters successfully? Do i need to change anything on pywps part or request xml? Waiting for suggestions, Thanks & Regards, Bala balavignesh <kbalavignesh@gmail.com> writes: > Whats the wrong in my code? Without seeing your code, all we could do is guess, poorly. Far better would be if you can construct a very small example, one that you post here so any reader here could run it, that demonstrates the behaviour you want explained. Don't forget to say what you expect the code to do differently. -- \ “I can picture in my mind a world without war, a world without | `\ hate. And I can picture us attacking that world, because they'd | _o__) never expect i...

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 99: ordinal not in range(128)
Hi, I don't know what I'm doing wrong here. I''m using Python 2.4 and py2exe. I get he following error: Traceback (most recent call last): File "notegui.pyc", line 34, in OnClose File "brain.pyc", line 61, in setNote File "points.pyc", line 151, in setNote File "point.pyc", line 100, in writeNote UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 99: ordinal not in range(128) The piece of code involved is: noteFileObj = open(noteFile, "wb") noteFileObj.write(...

'ascii' codec can't encode character u'\u2013'
Hi Using Python 2.3.4 + Feedparser 3.3 (a library to parse XML documents) I'm trying to parse a UTF-8 document with special characters like acute-accent vowels: -------- <?xml version=3D"1.0" encoding=3D"UTF-8" standalone=3D"yes"?> .... ------- But I get this error message: ------- UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 122: ordinal not in range(128) ------- when trying to execute a MySQL query: ---- query =3D "UPDATE blogs_news SET text =3D '" + text_extrated + "'WHER...

'ascii' codec can't encode character u'\xf3'
Hi, I get a piece of code of ogg123.py from the pyogg site, this is the code: ******************************* ogg_file = sys.argv[1] vorbis_file=ogg.vorbis.VorbisFile(ogg_file) comentarios = vorbis_file.comment() recognized_comments = ('Artist', 'Album', 'Title', 'Version', 'Organization', 'Genre', 'Description', 'Date', 'Location', 'Copyright', 'Vendor') comment_dict = {} for com in recognized_comments: comment_dict[string.upper(com)] = '%s: %%s' % com known_keys = comment_dict.keys(...

'^=' and '~='?
Hello, What is the difference between '^=' and '~='? Thanks, Duckhye ...

Fun with 'str' and 'bytes'
Hi all I want to create a cookie containing a session id. In python 2.6 I had the following - from __future__ import unicode_literals session_id = b64encode(urandom(20)) response_headers.append( (b'Set-Cookie', b'sid="{0}"'.format(session_id))) After upgrading to 3.2, the above lines generate this traceback - AttributeError: 'bytes' object has no attribute 'format' The best workaround I can come up with is the following - session_id = b64encode(urandom(20)) response_headers.append( (b'Set-Cookie', b'sid="' + sessi...

Why can't we 'tformfwd' a cp2tform(..., 'polynomial')
Hi, Just as an example: This is allowed xybase = reshape(randn(12,1),6,2); t_affine = cp2tform(xybase,xybase,'affine'); [x,y] = tformfwd(t_affine,xybase,xybase); but this t_poly = cp2tform(xybase,xybase,'polynomial',2); [x,y] = tformfwd(t_poly,xybase,xybase); gives an error "Function TFORMFWD expected T's forward_fcn field to be non- empty." I checked the code a bit and indeed, with the 'polynomial' case, the findPolynomialTransform() function has at its end trans = maketform('custom',2,2,[],@inv_polynomial,[A B]); wher...

python3; ftplib: TypeError: Can't convert 'bytes' object to str implicitly
This is the code I run (python 3.3) host = ... user = ... passwd = ... from ftplib import FTP ftp = FTP(host, user, passwd) ftp.mkd(b'NewDir') ftp.rmd(b'NewDir') This is the traceback Traceback (most recent call last): File "ftp-problem", line 9, in <module> ftp.mkd(b'NewDir') File "/usr/lib/python3.3/ftplib.py", line 612, in mkd resp = self.voidcmd('MKD ' + dirname) TypeError: Can't convert 'bytes' object to str implicitly The problem is that I do something like this in a backup progra...

i can't insert 'a''a' in a field with size 3
hi, i run INSERT INTO test (FIELD1) VALUES ('a''a') but DBMS oracle returns this error: ORA-01401: inserted value too large for column (FIELD1 size is 3!) what's the error? Fici wrote: > hi, > i run > INSERT INTO test (FIELD1) VALUES ('a''a') > but DBMS oracle returns this error: > ORA-01401: inserted value too large for column > (FIELD1 size is 3!) > what's the error? SQL> create table test ( 2 field1 VARCHAR2(3)); Table created. SQL> INSERT INTO test 2 (field1) 3 VALUES 4 ('a''a'); 1 row created. SQL> SELECT * FROM test; FIE --- a'a SQL> try the following in SQL*Plus: show define Post the result If you are not using SQL*Plus then your front-end tool is defective or needs to be reconfigured. -- Daniel A. Morgan Oracle Ace Director & Instructor University of Washington damorgan@x.washington.edu (replace x with u to respond) Puget Sound Oracle Users Group www.psoug.org On Mar 10, 6:38 pm, Fici <moretto.feder...@gmail.com> wrote: > hi, > i run > INSERT INTO test (FIELD1) VALUES ('a''a') > but DBMS oracle returns this error: > ORA-01401: inserted value too large for column > (FIELD1 size is 3!) > what's the error? Might be one of unicode charsets having each symbol more than one byte and column size defined in bytes not chars. Check DB charset and...

'''''''''''''The Running Update/Append Queries Using VBA code Ordeal''''''''''''''
Hello fellow programmers, I am trying to run an append/update query from code, a command button on a form initiates the queries. the format i am using is; _____________________________________________________ SELECT "criteria" FROM "criteria" WHERE "criteria" UPDATE/APPEND "field selections" RecordSource "qryExample" = above text strings" _______________________________________________________________________ When i am running a SELECT query in this manner it works fine with no problems, and accepts the values of specified linked for...

``awk '!a[$0]++' file'' and ``awk '{if(!($0 in rec)) {rec[$0]=1; print $0;}}' file ''
Hi all, Currently, I'm reading the book on awk programming language, but meet the following two examples which I cann't understand so well: awk '!a[$0]++' file and awk '{if(!($0 in rec)) {rec[$0]=1; print $0;}}' file Could someone here please give me some hints or explanations on the logic of above codes? Regards -- ..: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. In article <meuejm$gsf$1@aspen.stu.neva.ru>, Hongyi Zhao <hongyi.zhao@gmail.com> wrote: > Hi all, > > Currently, I'm reading the bo...

Re: '^=' and '~='? #8
32 libname erap 'T:\9SOW\AHRQ_E Rap\Data\E-RAP Data\December 2008'; NOTE: Libref ERAP was successfully assigned as follows: Engine: V9 Physical Name: T:\9SOW\AHRQ_E Rap\Data\E-RAP Data\December 2008 33 options nodate nonumber formdlim='-'; 34 /* Program: E-RAP Load XML to SAS with map v2.sas*/ 35 /************************************************************************* 36 Update path and file name below. 37 **************************************************************************/ 38 %let data_path = T:\9SOW\AHRQ_E Rap\Data\E-R...

which is more 'pythonic' / 'better' ?
hi, there are 2 versions of a simple code. which is preferred? === if len(line) >= (n+1): text = line[n] else: text = 'nothing' === === try: text = line[n] except IndexError: text = 'nothing' === which is the one you would use? thanks, gabor gabor wrote: > hi, > > there are 2 versions of a simple code. > which is preferred? > > > === > if len(line) >= (n+1): > text = line[n] > else: > text = 'nothing' > === > > > === > try: > text = line[n] > except IndexError: > text = '...

Web resources about - UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte - comp.lang.python

Resources last updated: 3/10/2016 7:10:45 PM