Repository: tonysimpson/nanomsg-python Branch: master Commit: 24e52b7d4847 Files: 24 Total size: 72.0 KB Directory structure: gitextract_uc4a31f2/ ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── _nanomsg_cpy/ │ └── wrapper.c ├── _nanomsg_ctypes/ │ └── __init__.py ├── appveyor.yml ├── build.cmd ├── docs/ │ ├── Makefile │ ├── conf.py │ └── index.rst ├── nanomsg/ │ ├── __init__.py │ ├── version.py │ └── wrapper.py ├── nanomsg_wrappers/ │ └── __init__.py ├── setup.py ├── test_utils/ │ ├── soaktest.py │ └── throughput.py ├── tests/ │ ├── __init__.py │ ├── test_general_socket_methods.py │ ├── test_pair.py │ ├── test_poll.py │ └── test_pubsub.py └── usr_local_setup.cfg ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject ================================================ FILE: .travis.yml ================================================ language: python python: - "3.2" - "3.3" - "3.4" - "2.7" - "2.6" # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors # Build steps taken from # https://github.com/nanomsg/nanomsg#build-it-with-cmake install: - git clone --quiet --depth=100 "https://github.com/nanomsg/nanomsg.git" ~/builds/nanomsg && pushd ~/builds/nanomsg && mkdir build && cd build && cmake .. && cmake --build . && ctest -C Debug . && sudo cmake --build . --target install && sudo ldconfig && popd # command to run tests, e.g. python setup.py test script: LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib python setup.py test ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2013 Tony Simpson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ nanomsg-python ============== Python library for [nanomsg](http://nanomsg.org/) which does not compromise on usability or performance. Like nanomsg this library is still experimental, the API is fairly stable but if you plan to use it at this time be prepared to get your hands dirty, fixes and enhancements are very welcome. The following versions of Python are supported CPython 2.6+, 3.2+ and Pypy 2.1.0+ Bugs and change requests can be made [here](https://github.com/tonysimpson/nanomsg-python/issues). nanommsg library in /usr/local ============================== If you're nanomsg is in /usr/local and your machine is not configured to find it there you can rename the usr_local_setup.cfg to setup.cfg to fix the problem. Example ======= ```python from __future__ import print_function from nanomsg import Socket, PAIR, PUB s1 = Socket(PAIR) s2 = Socket(PAIR) s1.bind('inproc://bob') s2.connect('inproc://bob') s1.send(b'hello nanomsg') print(s2.recv()) s1.close() s2.close() ``` Or if you don't mind nesting you can use Socket as a context manager ```python with Socket(PUB) as pub_socket: .... do something with pub_socket # socket is closed ``` The lower level API is also available if you need the additional control or performance, but it is harder to use. Error checking left out for brevity. ```python from nanomsg import wrapper as nn_wrapper from nanomsg import PAIR, AF_SP s1 = nn_wrapper.nn_socket(AF_SP, PAIR) s2 = nn_wrapper.nn_socket(AF_SP, PAIR) nn_wrapper.nn_bind(s1, 'inproc://bob') nn_wrapper.nn_connect(s2, 'inproc://bob') nn_wrapper.nn_send(s1, b'hello nanomsg', 0) result, buffer = nn_wrapper.nn_recv(s2, 0) print(bytes(buffer)) nn_wrapper.nn_term() ``` License ======= MIT Authors ======= [Tony Simpson](https://github.com/tonysimpson) ================================================ FILE: _nanomsg_cpy/wrapper.c ================================================ #include #include #include #include #ifdef WITH_NANOCONFIG #include #endif #if PY_MAJOR_VERSION >= 3 #define IS_PY3K #endif /* This might be a good idea or not */ #ifndef NO_CONCURRENY #define CONCURRENCY_POINT_BEGIN Py_BEGIN_ALLOW_THREADS #define CONCURRENCY_POINT_END Py_END_ALLOW_THREADS #else #define CONCURRENCY_POINT_BEGIN #define CONCURRENCY_POINT_END #endif /* defined to allow the same source for 2.6+ and 3.2+ */ #ifdef IS_PY3K #define Py_TPFLAGS_HAVE_CLASS 0L #define Py_TPFLAGS_HAVE_NEWBUFFER 0L #endif const static char MODULE_NAME[] = "_nanomsg_cpy"; typedef struct { PyObject_HEAD void *msg; size_t size; } Message; static void Message_dealloc(Message* self) { if (self->msg != NULL) { nn_freemsg(self->msg); } Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject* Message_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyErr_Format(PyExc_TypeError, "cannot create '%.100s' instances us nn_alloc instead", type->tp_name); return NULL; } static PyMemberDef Message_members[] = { {NULL} /* Sentinel */ }; static PyMethodDef Message_methods[] = { {NULL} /* Sentinel */ }; int Message_getbuffer(Message *self, Py_buffer *view, int flags) { if( self->msg == NULL) { PyErr_BadInternalCall(); return -1; } return PyBuffer_FillInfo(view, (PyObject*)self, self->msg, self->size, 0, flags); } #ifndef IS_PY3K static int Message_getreadbuffer(Message *self, int segment, void **ptrptr) { if(segment != 0 || self->msg == NULL) { PyErr_BadInternalCall(); return -1; } *ptrptr = ((Message*)self)->msg; return ((Message*)self)->size; } static int Message_getwritebuffer(Message *self, int segment, void **ptrptr) { if(segment != 0 || self->msg == NULL) { PyErr_BadInternalCall(); return -1; } *ptrptr = ((Message*)self)->msg; return ((Message*)self)->size; } static int Message_getsegcountproc(PyObject *self, int *lenp) { if (lenp != NULL) { *lenp = ((Message*)self)->size; } return 1; } #endif static PyBufferProcs Message_bufferproces = { #ifndef IS_PY3K (readbufferproc)Message_getreadbuffer, (writebufferproc)Message_getwritebuffer, (segcountproc)Message_getsegcountproc, NULL, #endif (getbufferproc)Message_getbuffer, NULL }; static PyObject * Message_repr(Message * obj) { return PyUnicode_FromFormat("<_nanomsg_cpy.Message size %zu, address %p >", obj->size, obj->msg); } static PyObject * Message_str(Message * obj) { return PyBytes_FromStringAndSize(obj->msg, obj->size); } static PyTypeObject MessageType = { PyVarObject_HEAD_INIT(NULL, 0) "_nanomsg_cpy.Message", /*tp_name*/ sizeof(Message), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Message_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)Message_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ (reprfunc)Message_str, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &Message_bufferproces, /*tp_as_buffer*/ Py_TPFLAGS_HAVE_CLASS | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_IS_ABSTRACT, /*tp_flags*/ "nanomsg allocated message wrapper supporting buffer protocol", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Message_methods, /* tp_methods */ Message_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ Message_new, /* tp_new */ }; static PyObject * _nanomsg_cpy_nn_errno(PyObject *self, PyObject *args) { return Py_BuildValue("i", nn_errno()); } static PyObject * _nanomsg_cpy_nn_strerror(PyObject *self, PyObject *args) { int error_number; if (!PyArg_ParseTuple(args, "i", &error_number)) return NULL; return Py_BuildValue("s", nn_strerror(error_number)); } static PyObject * _nanomsg_cpy_nn_socket(PyObject *self, PyObject *args) { int domain, protocol; if (!PyArg_ParseTuple(args, "ii", &domain, &protocol)) return NULL; return Py_BuildValue("i", nn_socket(domain, protocol)); } static PyObject * _nanomsg_cpy_nn_close(PyObject *self, PyObject *args) { int nn_result, socket; if (!PyArg_ParseTuple(args, "i", &socket)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_close(socket); CONCURRENCY_POINT_END return Py_BuildValue("i", nn_result); } #ifdef WITH_NANOCONFIG static PyObject * _nanomsg_cpy_nc_close(PyObject *self, PyObject *args) { int nn_result, socket; if (!PyArg_ParseTuple(args, "i", &socket)) return NULL; CONCURRENCY_POINT_BEGIN nc_close(socket); CONCURRENCY_POINT_END Py_RETURN_NONE; } #endif static const char _nanomsg_cpy_nn_setsockopt__doc__[] = "set a socket option\n" "\n" "socket - socket number\n" "level - option level\n" "option - option\n" "value - a readable byte buffer (not a Unicode string) containing the value\n" "returns - 0 on success or < 0 on error\n\n"; static PyObject * _nanomsg_cpy_nn_setsockopt(PyObject *self, PyObject *args) { int nn_result, socket, level, option; Py_buffer value; if (!PyArg_ParseTuple(args, "iiis*", &socket, &level, &option, &value)) return NULL; nn_result = nn_setsockopt(socket, level, option, value.buf, value.len); PyBuffer_Release(&value); return Py_BuildValue("i", nn_result); } static const char _nanomsg_cpy_nn_getsockopt__doc__[] = "retrieve a socket option\n" "\n" "socket - socket number\n" "level - option level\n" "option - option\n" "value - a writable byte buffer (e.g. a bytearray) which the option value " "will be copied to.\n" "returns - number of bytes copied or on error nunber < 0\n\n"; static PyObject * _nanomsg_cpy_nn_getsockopt(PyObject *self, PyObject *args) { int nn_result, socket, level, option; size_t length; Py_buffer value; if (!PyArg_ParseTuple(args, "iiiw*", &socket, &level, &option, &value)) return NULL; length = value.len; nn_result = nn_getsockopt(socket, level, option, value.buf, &length); PyBuffer_Release(&value); return Py_BuildValue("in", nn_result, length); } static PyObject * _nanomsg_cpy_nn_bind(PyObject *self, PyObject *args) { int socket; const char *address; if (!PyArg_ParseTuple(args, "is", &socket, &address)) return NULL; return Py_BuildValue("i", nn_bind(socket, address)); } static PyObject * _nanomsg_cpy_nn_connect(PyObject *self, PyObject *args) { int socket; const char *address; if (!PyArg_ParseTuple(args, "is", &socket, &address)) return NULL; return Py_BuildValue("i", nn_connect(socket, address)); } #ifdef WITH_NANOCONFIG static PyObject * _nanomsg_cpy_nc_configure(PyObject *self, PyObject *args) { int socket; const char *address; if (!PyArg_ParseTuple(args, "is", &socket, &address)) return NULL; return Py_BuildValue("i", nc_configure(socket, address)); } #endif static PyObject * _nanomsg_cpy_nn_shutdown(PyObject *self, PyObject *args) { int nn_result, socket, endpoint; if (!PyArg_ParseTuple(args, "ii", &socket, &endpoint)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_shutdown(socket, endpoint); CONCURRENCY_POINT_END return Py_BuildValue("i", nn_result); } static PyObject * _nanomsg_cpy_nn_send(PyObject *self, PyObject *args) { int nn_result, socket, flags; Py_buffer buffer; if (!PyArg_ParseTuple(args, "is*i", &socket, &buffer, &flags)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_send(socket, buffer.buf, buffer.len, flags); CONCURRENCY_POINT_END PyBuffer_Release(&buffer); return Py_BuildValue("i", nn_result); } static PyObject * _nanomsg_cpy_nn_recv(PyObject *self, PyObject *args) { int nn_result, socket, flags; Py_buffer buffer; Message* message; if(PyTuple_GET_SIZE(args) == 2) { if (!PyArg_ParseTuple(args, "ii", &socket, &flags)) return NULL; message = (Message*)PyType_GenericAlloc(&MessageType, 0); if(message == NULL) { return NULL; } CONCURRENCY_POINT_BEGIN nn_result = nn_recv(socket, &message->msg, NN_MSG, flags); CONCURRENCY_POINT_END if (nn_result < 0) { Py_DECREF((PyObject*)message); return Py_BuildValue("is", nn_result, NULL); } message->size = nn_result; return Py_BuildValue("iN", nn_result, message); } else { if(!PyArg_ParseTuple(args, "iw*i", &socket, &buffer, &flags)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_recv(socket, buffer.buf, buffer.len, flags); CONCURRENCY_POINT_END PyBuffer_Release(&buffer); return Py_BuildValue("iO", nn_result, PyTuple_GET_ITEM(args, 1)); } } static PyObject * _nanomsg_cpy_nn_device(PyObject *self, PyObject *args) { int socket_1, socket_2, nn_result; if (!PyArg_ParseTuple(args, "ii", &socket_1, &socket_2)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_device(socket_1, socket_2); CONCURRENCY_POINT_END return Py_BuildValue("i", nn_result); } static PyObject * _nanomsg_cpy_nn_poll(PyObject *self, PyObject *args) { int timeout_ms, res; PyObject *socket_event_dict, *sockets; Py_ssize_t socket_count; struct nn_pollfd *fds; Py_ssize_t pos; int i; PyObject *key, *value; PyObject *code; PyObject *result; if (!PyArg_ParseTuple(args, "O!i", &PyDict_Type, &socket_event_dict, &timeout_ms)) { return NULL; } sockets = PyDict_New(); socket_count = PyDict_Size(socket_event_dict); fds = malloc(sizeof(struct nn_pollfd)*socket_count); // build up fds array pos = 0; i = 0; while (PyDict_Next(socket_event_dict, &pos, &key, &value)) { fds[i].fd = (int)PyLong_AsLong(key); fds[i].events = (short)PyLong_AsLong(value); fds[i].revents = 0; i++; } CONCURRENCY_POINT_BEGIN res = nn_poll(fds, (int)socket_count, timeout_ms); CONCURRENCY_POINT_END // if success build result dictionary if (res > 0) { for(i = 0; i < socket_count; i++) { int fd = fds[i].fd; int revents = fds[i].revents; PyDict_SetItem(sockets, Py_BuildValue("i", fd), Py_BuildValue("i", revents)); } } free(fds); code = PyLong_FromUnsignedLong(res); result = PyTuple_Pack(2, code, sockets); return result; } static PyObject * _nanomsg_cpy_nn_term(PyObject *self, PyObject *args) { nn_term(); Py_RETURN_NONE; } #ifdef WITH_NANOCONFIG static PyObject * _nanomsg_cpy_nc_term(PyObject *self, PyObject *args) { nc_term(); Py_RETURN_NONE; } #endif static PyObject * _nanomsg_cpy_nn_allocmsg(PyObject *self, PyObject *args) { size_t size; int type; Message *message; if (!PyArg_ParseTuple(args, "ni", &size, &type)) return NULL; message = (Message*)PyType_GenericAlloc(&MessageType, 0); message->msg = nn_allocmsg(size, type); if (message->msg == NULL) { Py_DECREF((PyObject*)message); Py_RETURN_NONE; } message->size = size; return (PyObject*)message; } const char *nn_symbol (int i, int *value); static PyObject * _nanomsg_cpy_nn_symbols(PyObject *self, PyObject *args) { PyObject* py_list; const char *name; int value, i; py_list = PyList_New(0); for(i = 0; /*break inside loop */ ; i++) { name = nn_symbol(i,&value); if(name == NULL) { break; } PyList_Append(py_list, Py_BuildValue("si", name, value)); } return (PyObject*)py_list; } static PyMethodDef module_methods[] = { {"nn_errno", _nanomsg_cpy_nn_errno, METH_VARARGS, "retrieve the current errno"}, {"nn_strerror", _nanomsg_cpy_nn_strerror, METH_VARARGS, "convert an error number into human-readable string"}, {"nn_socket", _nanomsg_cpy_nn_socket, METH_VARARGS, "create an SP socket"}, {"nn_close", _nanomsg_cpy_nn_close, METH_VARARGS, "close an SP socket"}, {"nn_setsockopt", _nanomsg_cpy_nn_setsockopt, METH_VARARGS, _nanomsg_cpy_nn_setsockopt__doc__}, {"nn_getsockopt", _nanomsg_cpy_nn_getsockopt, METH_VARARGS, _nanomsg_cpy_nn_getsockopt__doc__}, {"nn_bind", _nanomsg_cpy_nn_bind, METH_VARARGS, "add a local endpoint to the socket"}, {"nn_connect", _nanomsg_cpy_nn_connect, METH_VARARGS, "add a remote endpoint to the socket"}, {"nn_shutdown", _nanomsg_cpy_nn_shutdown, METH_VARARGS, "remove an endpoint from a socket"}, {"nn_send", _nanomsg_cpy_nn_send, METH_VARARGS, "send a message"}, {"nn_recv", _nanomsg_cpy_nn_recv, METH_VARARGS, "receive a message"}, {"nn_device", _nanomsg_cpy_nn_device, METH_VARARGS, "start a device"}, {"nn_poll", _nanomsg_cpy_nn_poll, METH_VARARGS, "poll sockets"}, {"nn_term", _nanomsg_cpy_nn_term, METH_VARARGS, "notify all sockets about process termination"}, {"nn_allocmsg", _nanomsg_cpy_nn_allocmsg, METH_VARARGS, "allocate a message"}, {"nn_symbols", _nanomsg_cpy_nn_symbols, METH_VARARGS, "query the names and values of nanomsg symbols"}, #ifdef WITH_NANOCONFIG {"nc_configure", _nanomsg_cpy_nc_configure, METH_VARARGS, "configure socket using nanoconfig"}, {"nc_close", _nanomsg_cpy_nc_close, METH_VARARGS, "close an SP socket configured with nn_configure"}, {"nc_term", _nanomsg_cpy_nc_term, METH_VARARGS, "shut down nanoconfig worker thread"}, #endif {NULL, NULL, 0, NULL} }; #ifndef IS_PY3K PyMODINIT_FUNC init_nanomsg_cpy(void) { PyObject* m; if (PyType_Ready(&MessageType) < 0) return; m = Py_InitModule(MODULE_NAME, module_methods); if (m == NULL) return; Py_INCREF(&MessageType); PyModule_AddObject(m, "Message", (PyObject *)&MessageType); } #else static struct PyModuleDef _nanomsg_cpy_module = { PyModuleDef_HEAD_INIT, MODULE_NAME, NULL, -1, module_methods }; PyMODINIT_FUNC PyInit__nanomsg_cpy(void) { PyObject* m; if (PyType_Ready(&MessageType) < 0) return NULL; m = PyModule_Create(&_nanomsg_cpy_module); if(m != NULL) { PyModule_AddObject(m, "Message", (PyObject *)&MessageType); } return m; } #endif ================================================ FILE: _nanomsg_ctypes/__init__.py ================================================ from __future__ import division, absolute_import, print_function,\ unicode_literals import ctypes import platform import sys if sys.platform in ('win32', 'cygwin'): _functype = ctypes.WINFUNCTYPE _lib = ctypes.windll.nanomsg elif sys.platform == 'darwin': _functype = ctypes.CFUNCTYPE _lib = ctypes.cdll.LoadLibrary('libnanomsg.dylib') else: _functype = ctypes.CFUNCTYPE _lib = ctypes.cdll.LoadLibrary('libnanomsg.so') def _c_func_wrapper_factory(cdecl_text): def move_pointer_and_strip(type_def, name): if '*' in name: type_def += ' ' + name[:name.rindex('*')+1] name = name.rsplit('*', 1)[1] return type_def.strip(), name.strip() def type_lookup(type_def): types = { 'void': None, 'char *': ctypes.c_char_p, 'const char *': ctypes.c_char_p, 'int': ctypes.c_int, 'int *': ctypes.POINTER(ctypes.c_int), 'void *': ctypes.c_void_p, 'size_t': ctypes.c_size_t, 'size_t *': ctypes.POINTER(ctypes.c_size_t), 'struct nn_msghdr *': ctypes.c_void_p, 'struct nn_pollfd *': ctypes.c_void_p, } type_def_without_const = type_def.replace('const ','') if type_def_without_const in types: return types[type_def_without_const] elif (type_def_without_const.endswith('*') and type_def_without_const[:-1] in types): return ctypes.POINTER(types[type_def_without_const[:-1]]) else: raise KeyError(type_def) return types[type_def.replace('const ','')] a, b = [i.strip() for i in cdecl_text.split('(',1)] params, _ = b.rsplit(')',1) rtn_type, name = move_pointer_and_strip(*a.rsplit(' ', 1)) param_spec = [] for param in params.split(','): if param != 'void': param_spec.append(move_pointer_and_strip(*param.rsplit(' ', 1))) func = _functype(type_lookup(rtn_type), *[type_lookup(type_def) for type_def, _ in param_spec])( (name, _lib), tuple((2 if '**' in type_def else 1, name) for type_def, name in param_spec) ) func.__name__ = name return func _C_HEADER = """ NN_EXPORT int nn_errno (void); NN_EXPORT const char *nn_strerror (int errnum); NN_EXPORT const char *nn_symbol (int i, int *value); NN_EXPORT void nn_term (void); NN_EXPORT void *nn_allocmsg (size_t size, int type); NN_EXPORT int nn_freemsg (void *msg); NN_EXPORT int nn_socket (int domain, int protocol); NN_EXPORT int nn_close (int s); NN_EXPORT int nn_setsockopt (int s, int level, int option, const void \ *optval, size_t optvallen); NN_EXPORT int nn_getsockopt (int s, int level, int option, void *optval, \ size_t *optvallen); NN_EXPORT int nn_poll(struct nn_pollfd *fds, int nfds, int timeout); NN_EXPORT int nn_bind (int s, const char *addr); NN_EXPORT int nn_connect (int s, const char *addr); NN_EXPORT int nn_shutdown (int s, int how); NN_EXPORT int nn_send (int s, const void *buf, size_t len, int flags); NN_EXPORT int nn_recv (int s, void *buf, size_t len, int flags); NN_EXPORT int nn_sendmsg (int s, const struct nn_msghdr *msghdr, int flags); NN_EXPORT int nn_recvmsg (int s, struct nn_msghdr *msghdr, int flags); NN_EXPORT int nn_device (int s1, int s2);\ """.replace('NN_EXPORT', '') for cdecl_text in _C_HEADER.splitlines(): if cdecl_text.strip(): func = _c_func_wrapper_factory(cdecl_text) globals()['_' + func.__name__] = func def nn_symbols(): "query the names and values of nanomsg symbols" value = ctypes.c_int() name_value_pairs = [] i = 0 while True: name = _nn_symbol(i, ctypes.byref(value)) if name is None: break i += 1 name_value_pairs.append((name.decode('ascii'), value.value)) return name_value_pairs nn_errno = _nn_errno nn_errno.__doc__ = "retrieve the current errno" nn_strerror = _nn_strerror nn_strerror.__doc__ = "convert an error number into human-readable string" nn_socket = _nn_socket nn_socket.__doc__ = "create an SP socket" nn_close = _nn_close nn_close.__doc__ = "close an SP socket" nn_bind = _nn_bind nn_bind.__doc__ = "add a local endpoint to the socket" nn_connect = _nn_connect nn_connect.__doc__ = "add a remote endpoint to the socket" nn_shutdown = _nn_shutdown nn_shutdown.__doc__ = "remove an endpoint from a socket" def create_writable_buffer(size): """Returns a writable buffer. This is the ctypes implementation. """ return (ctypes.c_ubyte*size)() def nn_setsockopt(socket, level, option, value): """set a socket option socket - socket number level - option level option - option value - a readable byte buffer (not a Unicode string) containing the value returns - 0 on success or < 0 on error """ try: return _nn_setsockopt(socket, level, option, ctypes.addressof(value), len(value)) except (TypeError, AttributeError): buf_value = ctypes.create_string_buffer(value) return _nn_setsockopt(socket, level, option, ctypes.addressof(buf_value), len(value)) def nn_getsockopt(socket, level, option, value): """retrieve a socket option socket - socket number level - option level option - option value - a writable byte buffer (e.g. a bytearray) which the option value will be copied to returns - number of bytes copied or on error nunber < 0 """ if memoryview(value).readonly: raise TypeError('Writable buffer is required') size_t_size = ctypes.c_size_t(len(value)) rtn = _nn_getsockopt(socket, level, option, ctypes.addressof(value), ctypes.byref(size_t_size)) return (rtn, size_t_size.value) def nn_send(socket, msg, flags): "send a message" try: return _nn_send(socket, ctypes.addressof(msg), len(buffer(msg)), flags) except (TypeError, AttributeError): buf_msg = ctypes.create_string_buffer(msg) return _nn_send(socket, ctypes.addressof(buf_msg), len(msg), flags) def _create_message(address, length): class Message(ctypes.Union): _fields_ = [('_buf', ctypes.c_ubyte*length)] _len = length _address = address def __repr__(self): return '<_nanomsg_cpy.Message size %d, address 0x%x >' % ( self._len, self._address ) def __str__(self): return bytes(buffer(self)) def __del__(self): _nn_freemsg(self._address) self._len = 0 self._address = 0 return Message.from_address(address) def nn_allocmsg(size, type): "allocate a message" pointer = _nn_allocmsg(size, type) if pointer is None: return None return _create_message(pointer, size) class PollFds(ctypes.Structure): _fields_ = ("fd", ctypes.c_int), ("events", ctypes.c_short), ("revents", ctypes.c_short) def nn_poll(fds, timeout=-1): """ nn_pollfds :param fds: dict (file descriptor => pollmode) :param timeout: timeout in milliseconds :return: """ polls = [] for i, entry in enumerate(fds.items()): s = PollFds() fd, event = entry s.fd = fd s.events = event s.revents = 0 polls.append(s) poll_array = (PollFds*len(fds))(*polls) res = _nn_poll(poll_array, len(fds), int(timeout)) if res <= 0: return res, {} return res, {item.fd: item.revents for item in poll_array} def nn_recv(socket, *args): "receive a message" if len(args) == 1: flags, = args pointer = ctypes.c_void_p() rtn = _nn_recv(socket, ctypes.byref(pointer), ctypes.c_size_t(-1), flags) if rtn < 0: return rtn, None else: return rtn, _create_message(pointer.value, rtn) elif len(args) == 2: msg_buf, flags = args mv_buf = memoryview(msg_buf) if mv_buf.readonly: raise TypeError('Writable buffer is required') rtn = _nn_recv(socket, ctypes.addressof(msg_buf), len(mv_buf), flags) return rtn, msg_buf nn_device = _nn_device nn_device.__doc__ = "start a device" nn_term = _nn_term nn_term.__doc__ = "notify all sockets about process termination" try: if sys.platform in ('win32', 'cygwin'): _nclib = ctypes.windll.nanoconfig else: _nclib = ctypes.cdll.LoadLibrary('libnanoconfig.so') except OSError: pass # No nanoconfig, sorry else: # int nc_configure (int s, const char *addr) nc_configure = _functype(ctypes.c_int, ctypes.c_int, ctypes.c_char_p)( ('nc_configure', _nclib), ((1, 's'), (1, 'addr'))) nc_configure.__doc__ = "configure socket using nanoconfig" # void nc_close(int s); nc_close = _functype(None, ctypes.c_int)( ('nc_close', _nclib), ((1, 's'),)) nc_close.__doc__ = "close an SP socket configured with nn_configure" # void nc_term(); nc_term = _functype(None)( ('nc_term', _nclib), ()) nc_term.__doc__ = "shutdown nanoconfig worker thread" ================================================ FILE: appveyor.yml ================================================ # The template for this file was from https://packaging.python.org/appveyor/ environment: matrix: # For Python versions available on Appveyor, see # http://www.appveyor.com/docs/installed-software#python - PYTHON: "C:\\Python27" CMAKE_GENERATOR: "Visual Studio 9 2008" - PYTHON: "C:\\Python34" CMAKE_GENERATOR: "Visual Studio 10 2010" - PYTHON: "C:\\Python35" CMAKE_GENERATOR: "Visual Studio 14 2015" - PYTHON: "C:\\Python36" CMAKE_GENERATOR: "Visual Studio 14 2015" - PYTHON: "C:\\Python27" CMAKE_GENERATOR: "Visual Studio 9 2008 Win64" - PYTHON: "C:\\Python34-x64" CMAKE_GENERATOR: "Visual Studio 10 2010 Win64" - PYTHON: "C:\\Python35-x64" CMAKE_GENERATOR: "Visual Studio 14 2015 Win64" - PYTHON: "C:\\Python36-x64" CMAKE_GENERATOR: "Visual Studio 14 2015 Win64" install: # We need wheel installed to build wheels - "%PYTHON%\\python.exe -m pip install wheel" # Visual Studio 9 2008 does not come with stdint.h, so we'll copy over a # different version. We only need to do it whenever we're building with # 2008, but it doesn't hurt to copy it unconditionally. The first copy is to # build nanomsg, the second is to build the extension. - ps: cp "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include\\stdint.h" "C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\include\\stdint.h" - ps: cp "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include\\stdint.h" "C:\\Users\\appveyor\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\include\\stdint.h" - git clone https://github.com/nanomsg/nanomsg.git nanomsg-src - pwd - ps: pushd nanomsg-src - git checkout 1.0.0 - ps: mkdir build - ps: cd build - cmake -DNN_STATIC_LIB=ON -G"%CMAKE_GENERATOR%" .. - cmake --build . - cmake --build . --target install - ps: cp Debug\nanomsg.lib ..\.. - ps: popd - pwd build_script: - "%PYTHON%\\python.exe setup.py install" test_script: - "build.cmd %PYTHON%\\python.exe setup.py test" after_test: # build the wheel. # build.cmd sets up necessary variables for 64-bit builds - "build.cmd %PYTHON%\\python.exe setup.py bdist_wheel" artifacts: # bdist_wheel puts your built wheel in the dist directory - path: dist\* #on_success: # You can use this step to upload your artifacts to a public website. # See Appveyor's documentation for more details. Or you can simply # access your wheels from the Appveyor "artifacts" tab for your build. ================================================ FILE: build.cmd ================================================ @echo off :: To build extensions for 64 bit Python 3, we need to configure environment :: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of: :: MS Windows SDK for Windows 7 and .NET Framework 4 :: :: More details at: :: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows IF "%DISTUTILS_USE_SDK%"=="1" ( ECHO Configuring environment to build with MSVC on a 64bit architecture ECHO Using Windows SDK 7.1 "C:\Program Files\Microsoft SDKs\Windows\v7.1\Setup\WindowsSdkVer.exe" -q -version:v7.1 CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64 /release SET MSSdk=1 REM Need the following to allow tox to see the SDK compiler SET TOX_TESTENV_PASSENV=DISTUTILS_USE_SDK MSSdk INCLUDE LIB ) ELSE ( ECHO Using default MSVC build environment ) CALL %* ================================================ FILE: docs/Makefile ================================================ # Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nanomsg-python.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nanomsg-python.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/nanomsg-python" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nanomsg-python" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." ================================================ FILE: docs/conf.py ================================================ # -*- coding: utf-8 -*- # # nanomsg-python documentation build configuration file, created by # sphinx-quickstart on Fri Jan 23 17:17:17 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'nanomsg-python' copyright = u'2015, Tony Simpson ' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'nanomsg-pythondoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'nanomsg-python.tex', u'nanomsg-python Documentation', u'Tony Simpson \\textless{}agjasimpson@gmail.com\\textgreater{}', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'nanomsg-python', u'nanomsg-python Documentation', [u'Tony Simpson '], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'nanomsg-python', u'nanomsg-python Documentation', u'Tony Simpson ', 'nanomsg-python', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False ================================================ FILE: docs/index.rst ================================================ Welcome to nanomsg-python's documentation! ========================================== .. automodule:: nanomsg :members: :inherited-members: :undoc-members: .. automodule:: nanomsg_wrappers :members: :inherited-members: :undoc-members: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ================================================ FILE: nanomsg/__init__.py ================================================ from __future__ import division, absolute_import, print_function, unicode_literals from .version import __version__ from struct import Struct as _Struct import warnings from . import wrapper try: buffer except NameError: buffer = memoryview # py3 nanoconfig_started = False #Import constants into module with NN_ prefix stripped for name, value in wrapper.nn_symbols(): if name.startswith('NN_'): name = name[3:] globals()[name] = value if hasattr(wrapper, 'create_writable_buffer'): create_writable_buffer = wrapper.create_writable_buffer else: def create_writable_buffer(size): """Returns a writable buffer""" return bytearray(size) def create_message_buffer(size, type): """Create a message buffer""" rtn = wrapper.nn_allocmsg(size, type) if rtn is None: raise NanoMsgAPIError() return rtn class NanoMsgError(Exception): """Base Exception for all errors in the nanomsg python package """ pass class NanoMsgAPIError(NanoMsgError): """Exception for all errors reported by the C API. msg and errno are from nanomsg C library. """ __slots__ = ('msg', 'errno') def __init__(self): errno = wrapper.nn_errno() msg = wrapper.nn_strerror(errno) NanoMsgError.__init__(self, msg) self.errno, self.msg = errno, msg def _nn_check_positive_rtn(rtn): if rtn < 0: raise NanoMsgAPIError() return rtn class Device(object): """Create a nanomsg device to relay messages between sockets. If only one socket is supplied the device loops messages on that socket. """ def __init__(self, socket1, socket2=None): self._fd1 = socket1.fd self._fd2 = -1 if socket2 is None else socket2.fd def start(self): """Run the device in the current thread. This will not return until the device stops due to error or termination. """ _nn_check_positive_rtn(wrapper.nn_device(self._fd1, self._fd2)) def terminate_all(): """Close all sockets and devices""" global nanoconfig_started if nanoconfig_started: wrapper.nc_term() nanoconfig_started = False wrapper.nn_term() def poll(in_sockets, out_sockets, timeout=-1): """ Poll a list of sockets :param in_sockets: sockets for reading :param out_sockets: sockets for writing :param timeout: poll timeout in seconds, -1 is infinite wait :return: tuple (read socket list, write socket list) """ sockets = {} # reverse map fd => socket fd_sockets = {} for s in in_sockets: sockets[s.fd] = POLLIN fd_sockets[s.fd] = s for s in out_sockets: modes = sockets.get(s.fd, 0) sockets[s.fd] = modes | POLLOUT fd_sockets[s.fd] = s # convert to milliseconds or -1 if timeout >= 0: timeout_ms = int(timeout*1000) else: timeout_ms = -1 res, sockets = wrapper.nn_poll(sockets, timeout_ms) _nn_check_positive_rtn(res) read_list, write_list = [], [] for fd, result in sockets.items(): if (result & POLLIN) != 0: read_list.append(fd_sockets[fd]) if (result & POLLOUT) != 0: write_list.append(fd_sockets[fd]) return read_list, write_list class Socket(object): """Class wrapping nanomsg socket. protocol should be a nanomsg protocol constant e.g. nanomsg.PAIR This class supports being used as a context manager which should guarantee it is closed. e.g.: import time from nanomsg import PUB, Socket with Socket(PUB) as pub_socket: pub_socket.bind('tcp://127.0.0.1:49234') for i in range(100): pub_socket.send(b'hello all') time.sleep(0.5) #pub_socket is closed Socket.bind and Socket.connect return subclass of Endpoint which allow you to shutdown selected endpoints. The constructor also allows you to wrap existing sockets by passing in the socket fd instead of the protocol e.g.: from nanomsg import AF_SP, PAIR, Socket from nanomsg import wrapper as nn socket_fd = nn.nn_socket(AF_SP, PAIR) socket = Socket(socket_fd=socket_fd) """ _INT_PACKER = _Struct(str('i')) class _Endpoint(object): def __init__(self, socket, endpoint_id, address): self._endpoint_id = endpoint_id self._fdocket = socket self._address = address @property def address(self): return self._address def shutdown(self): self._fdocket._endpoints.remove(self) _nn_check_positive_rtn(wrapper.nn_shutdown(self._fdocket._fd, self._endpoint_id)) def __repr__(self): return '<%s socket %r, id %r, address %r>' % ( self.__class__.__name__, self._fdocket, self._endpoint_id, self._address ) class BindEndpoint(_Endpoint): pass class ConnectEndpoint(_Endpoint): pass class NanoconfigEndpoint(_Endpoint): def shutdown(self): raise NotImplementedError( "Shutdown of nanoconfig endpoint is not supported") def __init__(self, protocol=None, socket_fd=None, domain=AF_SP): if protocol is not None and socket_fd is not None: raise NanoMsgError('Only one of protocol or socket_fd should be ' 'passed to the Socket constructor') if protocol is not None: self._fd = _nn_check_positive_rtn( wrapper.nn_socket(domain, protocol) ) else: self._fd = socket_fd self._endpoints = [] def _get_send_fd(self): return self.get_int_option(SOL_SOCKET, SNDFD) def _get_recv_fd(self): return self.get_int_option(SOL_SOCKET, RCVFD) def _get_linger(self): return self.get_int_option(SOL_SOCKET, LINGER) def _set_linger(self, value): return self.set_int_option(SOL_SOCKET, LINGER, value) def _get_send_buffer_size(self): return self.get_int_option(SOL_SOCKET, SNDBUF) def _set_send_buffer_size(self, value): return self.set_int_option(SOL_SOCKET, SNDBUF, value) def _get_recv_buffer_size(self): return self.get_int_option(SOL_SOCKET, RCVBUF) def _set_recv_buffer_size(self, value): return self.set_int_option(SOL_SOCKET, RCVBUF, value) def _get_send_timeout(self): return self.get_int_option(SOL_SOCKET, SNDTIMEO) def _set_send_timeout(self, value): return self.set_int_option(SOL_SOCKET, SNDTIMEO, value) def _get_recv_timeout(self): return self.get_int_option(SOL_SOCKET, RCVTIMEO) def _set_recv_timeout(self, value): return self.set_int_option(SOL_SOCKET, RCVTIMEO, value) def _get_reconnect_interval(self): return self.get_int_option(SOL_SOCKET, RECONNECT_IVL) def _set_reconnect_interval(self, value): return self.set_int_option(SOL_SOCKET, RECONNECT_IVL, value) def _get_reconnect_interval_max(self): return self.get_int_option(SOL_SOCKET, RECONNECT_IVL_MAX) def _set_reconnect_interval_max(self, value): return self.set_int_option(SOL_SOCKET, RECONNECT_IVL_MAX, value) send_fd = property(_get_send_fd, doc='Send file descripter') recv_fd = property(_get_recv_fd, doc='Receive file descripter') linger = property(_get_linger, _set_linger, doc='Socket linger in ' 'milliseconds (0.001 seconds)') recv_buffer_size = property(_get_recv_buffer_size, _set_recv_buffer_size, doc='Receive buffer size in bytes') send_buffer_size = property(_get_send_buffer_size, _set_send_buffer_size, doc='Send buffer size in bytes') send_timeout = property(_get_send_timeout, _set_send_timeout, doc='Send timeout in milliseconds (0.001 seconds)') recv_timeout = property(_get_recv_timeout, _set_recv_timeout, doc='Receive timeout in milliseconds (0.001 ' 'seconds)') reconnect_interval = property( _get_reconnect_interval, _set_reconnect_interval, doc='Base interval between connection failure and reconnect' ' attempt in milliseconds (0.001 seconds).' ) reconnect_interval_max = property( _get_reconnect_interval_max, _set_reconnect_interval_max, doc='Max reconnect interval - see C API documentation.' ) @property def fd(self): """Socket file descripter. Note this is not an OS file descripter (see .send_fd, .recv_fd). """ return self._fd @property def endpoints(self): """Endpoints list """ return list(self._endpoints) @property def uses_nanoconfig(self): return (self._endpoints and isinstance(self._endpoints[0], Socket.NanoconfigEndpoint)) def bind(self, address): """Add a local endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_bind(self._fd, address) ) ep = Socket.BindEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep def connect(self, address): """Add a remote endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_connect(self.fd, address) ) ep = Socket.ConnectEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep def configure(self, address): """Configure socket's addresses with nanoconfig""" global nanoconfig_started if len(self._endpoints): raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nc_configure(self.fd, address) ) if not nanoconfig_started: nanoconfig_started = True ep = Socket.NanoconfigEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep def close(self): """Close the socket""" if self.is_open(): fd = self._fd self._fd = -1 if self.uses_nanoconfig: wrapper.nc_close(fd) else: _nn_check_positive_rtn(wrapper.nn_close(fd)) def is_open(self): """Returns true if the socket has a valid socket id. If the underlying socket is closed by some other means than Socket.close this method may return True when the socket is actually closed. """ return self.fd >= 0 def recv(self, buf=None, flags=0): """Recieve a message.""" if buf is None: rtn, out_buf = wrapper.nn_recv(self.fd, flags) else: rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags) _nn_check_positive_rtn(rtn) return bytes(buffer(out_buf))[:rtn] def set_string_option(self, level, option, value): _nn_check_positive_rtn(wrapper.nn_setsockopt(self.fd, level, option, value)) def set_int_option(self, level, option, value): buf = create_writable_buffer(Socket._INT_PACKER.size) Socket._INT_PACKER.pack_into(buf, 0, value) _nn_check_positive_rtn(wrapper.nn_setsockopt(self.fd, level, option, buf)) def get_int_option(self, level, option): size = Socket._INT_PACKER.size buf = create_writable_buffer(size) rtn, length = wrapper.nn_getsockopt(self._fd, level, option, buf) _nn_check_positive_rtn(rtn) if length != size: raise NanoMsgError(('Returned option size (%r) should be the same' ' as size of int (%r)') % (length, size)) return Socket._INT_PACKER.unpack_from(buffer(buf))[0] def get_string_option(self, level, option, max_len=16*1024): buf = create_writable_buffer(max_len) rtn, length = wrapper.nn_getsockopt(self._fd, level, option, buf) _nn_check_positive_rtn(rtn) return bytes(buffer(buf))[:length] def send(self, msg, flags=0): """Send a message""" _nn_check_positive_rtn(wrapper.nn_send(self.fd, msg, flags)) def __enter__(self): return self def __exit__(self, *args): self.close() def __repr__(self): return '<%s fd %r, connected to %r, bound to %r>' % ( self.__class__.__name__, self.fd, [i.address for i in self.endpoints if type(i) is Socket.ConnectEndpoint], [i.address for i in self.endpoints if type(i) is Socket.BindEndpoint], ) def __del__(self): try: self.close() except NanoMsgError: pass ================================================ FILE: nanomsg/version.py ================================================ __version__ = '1.0' ================================================ FILE: nanomsg/wrapper.py ================================================ from __future__ import division, absolute_import, print_function, unicode_literals from nanomsg_wrappers import load_wrapper as _load_wrapper _wrapper = _load_wrapper() globals().update(_wrapper.__dict__) ================================================ FILE: nanomsg_wrappers/__init__.py ================================================ from __future__ import division, absolute_import, print_function, unicode_literals from platform import python_implementation import pkgutil import importlib import warnings _choice = None def set_wrapper_choice(name): global _choice _choice = name def load_wrapper(): if _choice is not None: return importlib.import_module('_nanomsg_' + _choice) default = get_default_for_platform() try: return importlib.import_module('_nanomsg_' + default) except ImportError: warnings.warn(("Could not load the default wrapper for your platform: " "%s, performance may be affected!") % (default,)) return importlib.import_module('_nanomsg_ctypes') def get_default_for_platform(): if python_implementation() == 'CPython': return 'cpy' else: return 'ctypes' def list_wrappers(): return [module_name.split('_',2)[-1] for _, module_name, _ in pkgutil.iter_modules() if module_name.startswith('_nanomsg_')] ================================================ FILE: setup.py ================================================ from __future__ import division, absolute_import, print_function, unicode_literals import os import platform import sys from setuptools import setup from distutils.core import Extension from distutils.command.build_ext import build_ext with open(os.path.join('nanomsg','version.py')) as f: exec(f.read()) libraries = [str('nanomsg')] # add additional necessary library/include path info if we're on Windows if sys.platform in ("win32", "cygwin"): libraries.extend([str('ws2_32'), str('advapi32'), str('mswsock')]) # nanomsg installs to different directory based on architecture arch = platform.architecture()[0] if arch == "64bit": include_dirs=[r'C:\Program Files\nanomsg\include',] else: include_dirs=[r'C:\Program Files (x86)\nanomsg\include',] else: include_dirs = None try: import ctypes if sys.platform in ('win32', 'cygwin'): _lib = ctypes.windll.nanoconfig elif sys.platform == 'darwin': _lib = ctypes.cdll.LoadLibrary('libnanoconfig.dylib') else: _lib = ctypes.cdll.LoadLibrary('libnanoconfig.so') except OSError: # Building without nanoconfig; need to turn NN_STATIC_LIB on define_macros = [('NN_STATIC_LIB','ON')] else: # Building with nanoconfig libraries.append(str('nanoconfig')) define_macros = [('WITH_NANOCONFIG', '1')] cpy_extension = Extension(str('_nanomsg_cpy'), define_macros=define_macros, sources=[str('_nanomsg_cpy/wrapper.c')], libraries=libraries, include_dirs=include_dirs, ) install_requires = [] try: import importlib except ImportError: install_requires.append('importlib') setup( name='nanomsg', version=__version__, packages=[str('nanomsg'), str('_nanomsg_ctypes'), str('nanomsg_wrappers')], ext_modules=[cpy_extension], install_requires=install_requires, description='Python library for nanomsg.', classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", ], author='Tony Simpson', author_email='agjasimpson@gmail.com', url='https://github.com/tonysimpson/nanomsg-python', keywords=['nanomsg', 'driver'], license='MIT', test_suite="tests", ) ================================================ FILE: test_utils/soaktest.py ================================================ import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( SUB, PUB, SUB_SUBSCRIBE, Socket ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") from nanomsg import Socket, BUS, PAIR import sys import random from itertools import count with Socket(PAIR) as socket1: with Socket(PAIR) as socket2: socket1.bind(SOCKET_ADDRESS) socket2.connect(SOCKET_ADDRESS) for i in count(1): msg = b''.join(chr(random.randint(0,255)) for i in range(1024*1024)) socket1.send(msg) res = socket2.recv() print i if msg != res: for num, (c1, c2) in enumerate(zip(msg, res)): if c1 != c2: print 'diff at', num, repr(c1), repr(c2) sys.exit() ================================================ FILE: test_utils/throughput.py ================================================ from __future__ import division, absolute_import, print_function,\ unicode_literals import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform WRAPPER = os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform()) set_wrapper_choice(WRAPPER) from nanomsg import ( PAIR, Socket, create_message_buffer ) from nanomsg.wrapper import ( nn_send, nn_recv ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") import time BUFFER_SIZE = eval(os.environ.get('NANOMSG_PY_TEST_BUFFER_SIZE', "1024")) msg = create_message_buffer(BUFFER_SIZE, 0) DURATION = 10 print(('Working NANOMSG_PY_TEST_BUFFER_SIZE %d NANOMSG_PY_TEST_WRAPPER %r ' 'NANOMSG_PY_TEST_ADDRESS %r') % (BUFFER_SIZE, WRAPPER, SOCKET_ADDRESS)) count = 0 start_t = time.time() with Socket(PAIR) as socket1: with Socket(PAIR) as socket2: socket1.bind(SOCKET_ADDRESS) socket2.connect(SOCKET_ADDRESS) while time.time() < start_t + DURATION: c = chr(count % 255) memoryview(msg)[0] = c socket1.send(msg) res = socket2.recv(msg) assert res[0] == c count += 1 stop_t = time.time() print('Socket API throughput with checks - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,)) count = 0 start_t = time.time() with Socket(PAIR) as socket1: with Socket(PAIR) as socket2: socket1.bind(SOCKET_ADDRESS) socket2.connect(SOCKET_ADDRESS) while time.time() < start_t + DURATION: nn_send(socket1.fd, msg, 0) nn_recv(socket2.fd, msg, 0) count += 1 stop_t = time.time() print('Raw thoughtput no checks - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,)) ================================================ FILE: tests/__init__.py ================================================ ================================================ FILE: tests/test_general_socket_methods.py ================================================ import unittest import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( PAIR, Socket, SNDBUF, SOL_SOCKET ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") class TestGeneralSocketMethods(unittest.TestCase): def setUp(self): self.socket = Socket(PAIR) def tearDown(self): self.socket.close() def test_bind(self): endpoint = self.socket.bind(SOCKET_ADDRESS) self.assertNotEqual(None, endpoint) def test_connect(self): endpoint = self.socket.connect(SOCKET_ADDRESS) self.assertNotEqual(None, endpoint) def test_is_open_is_true_when_open(self): self.assertTrue(self.socket.is_open()) def test_is_open_is_false_when_closed(self): self.socket.close() self.assertFalse(self.socket.is_open()) def test_set_and_get_int_option(self): expected = 500 self.socket.set_int_option(SOL_SOCKET, SNDBUF, expected) actual = self.socket.get_int_option(SOL_SOCKET, SNDBUF) self.assertEqual(expected, actual) if __name__ == '__main__': unittest.main() ================================================ FILE: tests/test_pair.py ================================================ import unittest import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( PAIR, Socket ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") class TestPairSockets(unittest.TestCase): def test_send_recv(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) sent = b'ABC' s2.send(sent) recieved = s1.recv() self.assertEqual(sent, recieved) def test_send_recv_with_embeded_nulls(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) sent = b'ABC\x00DEFEDDSS' s2.send(sent) recieved = s1.recv() self.assertEqual(sent, recieved) def test_send_recv_large_message(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) sent = b'B'*(1024*1024) s2.send(sent) recieved = s1.recv() self.assertEqual(sent, recieved) if __name__ == '__main__': unittest.main() ================================================ FILE: tests/test_poll.py ================================================ import unittest import os import uuid import time from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( PAIR, DONTWAIT, SOL_SOCKET, SNDBUF, poll, Socket, NanoMsgAPIError ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://{0}".format(uuid.uuid4())) class TestPoll(unittest.TestCase): def test_read_poll(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) r, _ = poll([s1, s2], [], 0) self.assertEqual(0, len(r), "Precondition nothing to read") sent = b'ABC' s2.send(sent) r, _ = poll([s1, s2], [], 0) self.assertTrue(s1 in r, "Socket is in read list") received = s1.recv() def test_write_poll(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) r, w = poll([], [s1, s2], 2) self.assertEqual(2, len(w), "Precondition nothing to read") sent = b'ABCD' # minimum send size snd_buf_size = 128*1024 s2.set_int_option(SOL_SOCKET, SNDBUF, snd_buf_size) # send until full for i in range(snd_buf_size//len(sent)+1): try: s2.send(sent, DONTWAIT) except: pass # poll r, w = poll([], [s1, s2], 0) self.assertTrue(s2 not in w, "Socket is in write list") received = s1.recv() def test_poll_timeout(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) start_time = time.time() timeout = .05 r, _ = poll([s1, s2], [], timeout) end_time = time.time() self.assertTrue(end_time-start_time-timeout < .030) self.assertEqual(0, len(r), "No sockets to read") if __name__ == '__main__': unittest.main() ================================================ FILE: tests/test_pubsub.py ================================================ import unittest import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( SUB, PUB, SUB_SUBSCRIBE, Socket ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") class TestPubSubSockets(unittest.TestCase): def test_subscribe_works(self): with Socket(PUB) as s1: with Socket(SUB) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) s2.set_string_option(SUB, SUB_SUBSCRIBE, 'test') s1.send('test') s2.recv() s1.send('a') # should not get received expected = b'test121212' s1.send(expected) actual = s2.recv() self.assertEquals(expected, actual) if __name__ == '__main__': unittest.main() ================================================ FILE: usr_local_setup.cfg ================================================ [build_ext] include_dirs=/usr/local/include library_dirs=/usr/local/lib rpath=/usr/local/lib