Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does zmq.setsockopt_string complain about default 'ascii' code?

I'm trying to figure out if my dev environment is somehow screwed up, since "it works on [my colleagues] computer" but not mine. Instead of tackling the 'meat' of the problem, I'm working on the first funny thing I've spotted.

I have a bit of code that doesn't make sense why one call would work, and the other not:

import sys
import zmq

if __name__ == "__main__":
    print sys.getdefaultencoding()  # Displays 'ascii'

    zContext = zmq.Context()
    zSocket = zContext.socket(zmq.SUB)

    # This works.
    zSocket.setsockopt_string( zmq.SUBSCRIBE, "Hello".decode('ascii'))

    # This fails with error... why?
    # raise TypeError("unicode strings only")
    #
    # Shouldn't the default encoding for "Hello" be ascii?
    # zSocket.setsockopt_string( zmq.SUBSCRIBE, "Hello")

    zSocket.connect( "tcp://localhost:5000")

I'm assuming for the working call to setsockopt_string, that I am passing an array of ascii characters. In the broken code, I must be sending something not ascii, but not unicode. How would I know what is getting passed to setsockopt_string?

Maybe this isn't even the questions to ask. I'm just rather confused.

Any help would be great.

Here's my environment:

python --version
Python 2.7.3
#1 SMP Debian 3.2.57-3+deb7u2 x86_64 GNU/Linux

thanks.

like image 385
Bitdiot Avatar asked Aug 07 '14 00:08

Bitdiot


People also ask

What is context in Zmq?

Technically, the context is the container for all sockets in a single process, and it acts as the transport for inproc sockets, which are the fastest way to connect threads in one process. If at runtime a process has two contexts, these are like separate ØMQ instances.

What is Zmq Python?

ZeroMQ (also spelled ØMQ, 0MQ or ZMQ) is a high-performance asynchronous messaging library, aimed at use in distributed or concurrent applications. It provides a message queue, but unlike message-oriented middleware, a ZeroMQ system can run without a dedicated message broker.


1 Answers

The problem encountered caused by the unicode/str value set to the setsockopt_string method, a quick fix would be:

zSocket.setsockopt_string(zmq.SUBSCRIBE, b"Hello")

This will pass bytes instead of string, or if you have variable there, then you should write it this way:

zSocket.setsockopt_string(
    zmq.SUBSCRIBE,
    bytes("Hello", encoding="latin-1")
)

This would work on both python 2 and 3

like image 168
HXH Avatar answered Oct 11 '22 12:10

HXH