ZMQ Socket TypeError: unicode strings only Error: is there a fix?

ZMQ Socket TypeError: unicode strings only Error: is there a fix?

尝试在命令提示符中运行以下Python代码: 我正在使用 Python 2.

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

能否请您提供解决方案?

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

如果你只 运行 你的代码在 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