TypeError: writelines() argument must be a sequence of strings

10,345

Solution 1

I finally figure this out.

This happend when:

try:
   raise Exception(u'Error with unicode chars')
except:
  sys.stderr.write(u'%s\n\n' % e)

I hack with this (from activestate community):

def safe_unicode(obj, * args):
    """ return the unicode representation of obj """
    try:
        return unicode(obj, * args)
    except UnicodeDecodeError:
        # obj is byte string
        ascii_text = str(obj).encode('string_escape')
        return unicode(ascii_text)

def safe_str(obj):
    """ return the byte string representation of obj """
    try:
        return str(obj)
    except UnicodeEncodeError:
        # obj is unicode
        return unicode(obj).encode('unicode_escape')


 #code
 except Exception,e:
        sys.stderr.write(u'%s\n\n' % safe_unicode(safe_str(e)))

Solution 2

My solution to this was to encode the text in UTF-8

file.writelines("some unicode text here".encode('utf-8'))
Share:
10,345
mamcx
Author by

mamcx

CEO & Developer of "El malabarista", maker of the POS for the iPhone BestSeller. 12+ years of experience creating software in use for more than +2000 users in my country. Experience in Python, Django, Web apps, APIs, .NET, Objective-C, iPhone/iPad development, RemObjects & more. CV: http://careers.stackoverflow.com/cv/employer/20796

Updated on June 08, 2022

Comments

  • mamcx
    mamcx almost 2 years

    I have a weird error when try to redirect a exception to STDERR.

    I have a script that is use to load several "plugins", working as main entry program. The plugins do stuff like connect to databases, parsing text data, connect to web services, etc...

    Is like this:

       try:
            Run plugins here...
            #All was ok!
            print "Ok!"
            sys.exit(0)
        except Exception,e:
            sys.stderr.writelines([unicode(e),u'\n',u'\n'])
    
            traceback.print_exc(file=sys.stderr)
            sys.exit(-1)
    

    This is executed in the command-line, and sometimes I get the error:

    TypeError: writelines() argument must be a sequence of strings
    

    I have no clue how in this earth a Exception is not returning as a string here.