TypeError: writelines() 参数必须是字符串序列

3 投票
4 回答
10635 浏览
提问于 2025-04-16 02:05

我在尝试将一个错误信息重定向到标准错误输出(STDERR)时遇到了一个奇怪的错误。

我有一个脚本,用来加载几个“插件”,这个脚本就像是主程序入口。这些插件的功能包括连接数据库、解析文本数据、连接网络服务等等……

大概是这样的:

   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)

这个脚本是在命令行中执行的,有时候我会遇到这样的错误:

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

我完全搞不懂,为什么这里的异常(Exception)没有以字符串的形式返回。

4 个回答

0

为了更好地了解发生了什么,可以把出问题的那行代码放在一个try:except: ...的结构里。在except部分,执行以下代码:

print repr(e), repr(unicode(e))

为什么你需要用unicode字符串,而不是str字符串呢?

7

我解决这个问题的方法是把文本编码成UTF-8格式。

file.writelines("some unicode text here".encode('utf-8'))
2

我终于搞明白这个问题了。

这个情况发生在:

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

我用这个方法解决了(来自activestate社区):

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)))

撰写回答