2016-12-31 72 views
1

試圖運行在命令提示符下Python代碼: 我使用Python 2ZMQ套接字類型錯誤:僅Unicode字符串錯誤:是否有修復?

import zmq 
context = zmq.Context() 
socket = context.socket(zmq.SUB) 
socket.connect('tcp://0.0.0.0.:6667') 
socket.setsockopt_string(zmq.SUBSCRIBE, 'value') 

並得到以下錯誤,當我執行:

socket.setsockopt_string(zmq.SUBSCRIBE, value) File "C:\Program Files\Anaconda2\lib\site-packages\zmq\sugar\socket.py", line 192, in >set_string 
raise TypeError("unicode strings only") TypeError: unicode strings only 

你能請告知在方案?

+0

那麼,你有沒有試過將[Unicode字符串](https://docs.python.org/2/howto/unicode.html#unicode-literals-in-python-source-code)傳遞給'setsockopt_string()'? –

+0

也許這可以幫助:http://stackoverflow.com/questions/4182603/python-how-to-convert-a-string-to-utf-8 – PerunSS

+0

我已經嘗試所有建議的方法在https://docs.python .org等/ 2/HOWTO/unicode.html#Unicode的文字合蟒源代碼 – stats999

回答

0

socket.setsockopt_string接受unicode optval的字符串。

,如果你只運行在python2你的代碼,你應該使用

sock.setsockopt(zmq.SUBSCRIBE, b"value")

,如果你想同時支持python2和python3,你可以使用

try: 
    sock.setsockopt(zmq.SUBSCRIBE, b'value') 
except TypeError: 
    sock.setsockopt_string(zmq.SUBSCRIBE, b'value') 

看看http://pyzmq.readthedocs.io/en/latest/unicode.html