TypeError:必须是字符串,而不是unicode

Use*_*erX 5 python unicode pickle

我有这个代码:

...
msgdict = {'datafile': datafile, 'mapper': mapper, 'reducer':reducer}
msg = cPickle.dumps(msgdict)
print msg   
Run Code Online (Sandbox Code Playgroud)

打印消息我得到这个:

(dp1
S'mapper'
p2
(S's3n://myFolder/mapper.py'
p3
tp4
sS'datafile'
p5
(S's3n://myFolder/test.txt'
p6
tp7
sS'reducer'
p8
(S's3n://myFolder/reducer.py'
p9
tp10
s.
Run Code Online (Sandbox Code Playgroud)

然后我试图得到我的内容:

for i in range(count):
    m = q[0].read()
    # this print returns a object Message
    print m 
    # m.get_body()) returns the same of print msg above
    msg = cPickle.loads(m.get_body()) 
Run Code Online (Sandbox Code Playgroud)

但我有这个错误:

msg = cPickle.loads(m.get_body())       
TypeError: must be string, not unicode
Run Code Online (Sandbox Code Playgroud)

有人知道如何解决这个错误?

A.J*_*pal 7

尝试使用以下内容替换该行:

msg = cPickle.loads(str(m.get_body()))
Run Code Online (Sandbox Code Playgroud)

通过强制str()转换m.get_body(),它确保如果字符串是unicode,它会将其转换为字符串.