These two python script files are modified from pyzmq samples
topics_pub.py
#!/usr/bin/env python
"""Simple example of publish/subscribe illustrating topics.
Publisher and subscriber can be started in any order, though if publisher
starts first, any messages sent before subscriber starts are lost. More than
one subscriber can listen, and they can listen to different topics.
Topic filtering is done simply on the start of the string, e.g. listening to
's' will catch 'sports...' and 'stocks' while listening to 'w' is enough to
catch 'weather'.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2010 Brian Granger
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distributed as part of this software.
#-----------------------------------------------------------------------------
import itertools
import sys
import time
import zmq
def main():
if len (sys.argv) != 2:
print('usage: publisher <bind-to>')
sys.exit (1)
bind_to = sys.argv[1]
all_topics = ['sports.general','sports.football','sports.basketball',
'stocks.general','stocks.GOOG','stocks.AAPL',
'weather']
ctx = zmq.Context()
s = ctx.socket(zmq.PUB)
s.bind(bind_to)
print("Starting broadcast on topics:")
print(" %s" % all_topics)
print("Hit Ctrl-C to stop broadcasting.")
print("Waiting so subscriber sockets can connect...")
print()
time.sleep(1.0)
msg_counter = itertools.count()
try:
for topic in itertools.cycle(all_topics):
msg_body = str(next(msg_counter))
print(" Topic: {}, msg:{}".format(topic, msg_body))
s.send_multipart([topic.encode(), msg_body.encode()])
# short wait so we don't hog the cpu
time.sleep(0.1)
except KeyboardInterrupt:
pass
print("Waiting for message queues to flush...")
time.sleep(0.5)
print("Done.")
if __name__ == "__main__":
main()
topics_sub.py
#!/usr/bin/env python
"""Simple example of publish/subscribe illustrating topics.
Publisher and subscriber can be started in any order, though if publisher
starts first, any messages sent before subscriber starts are lost. More than
one subscriber can listen, and they can listen to different topics.
Topic filtering is done simply on the start of the string, e.g. listening to
's' will catch 'sports...' and 'stocks' while listening to 'w' is enough to
catch 'weather'.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2010 Brian Granger, Fernando Perez
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distributed as part of this software.
#-----------------------------------------------------------------------------
import sys
import time
import zmq
import numpy
def main():
if len (sys.argv) < 2:
print ('usage: subscriber <connect_to> [topic topic ...]')
sys.exit (1)
connect_to = sys.argv[1]
topics = sys.argv[2:]
ctx = zmq.Context()
s = ctx.socket(zmq.SUB)
print(connect_to)
s.connect(connect_to)
# manage subscriptions
if not topics:
print("Receiving messages on ALL topics...")
s.setsockopt(zmq.SUBSCRIBE,'')
else:
print("Receiving messages on topics: %s ..." % topics)
for t in topics:
s.setsockopt_string(zmq.SUBSCRIBE,t)
print()
try:
while True:
topic, msg = s.recv_multipart()
print(' Topic: %s, msg:%s' % (topic, msg))
except KeyboardInterrupt:
pass
print("Done.")
if __name__ == "__main__":
main()
Showing posts with label python. Show all posts
Showing posts with label python. Show all posts
Sunday, September 25, 2016
Monday, July 25, 2016
pybee python ios
https://github.com/pybee/Python-Apple-support
#import "Python/Python.h"
http://stackoverflow.com/questions/9749260/python-for-ios-interpreter
A little trip to Ubuntu 16.04
Install Python 3.5
helloworld.c
build
Calling Python from C and fetching return values
Python: sample.py
sample.c
Objective-C
#import "Python/Python.h"
http://stackoverflow.com/questions/9749260/python-for-ios-interpreter
A little trip to Ubuntu 16.04
Install Python 3.5
1
sudo apt-get install python3 python3-dev
helloworld.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <Python.h> int main(int argc, char *argv[]) { wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print('Today is', ctime(time()))\n"); Py_Finalize(); PyMem_RawFree(program); return 0; }
build
1 3
gcc -c hellowworld.c gcc helloworld.o $(/usr/bin/python3.5-config --ldflags)
Calling Python from C and fetching return values
Python: sample.py
1 2 3
# Returns the sum of two numbers. def add(a, b): return a+b
sample.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <python3.5/Python.h> #include <stdio.h>
int main(int argc, char* argv[])
{ char localPath[40] = "\/home\/XXX\/XXX\/"; printf("Calling Python to find the sum of 2 and 2.\n"); // Initialize the Python interpreter. Py_Initialize(); // Create some Python objects that will later be assigned values. PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; // Convert the file name to a Python string. pName = PyUnicode_FromString("sample"); PyObject *sys_path = PySys_GetObject("path"); PyList_Append(sys_path, PyUnicode_FromString(localPath)); // Import the file as a Python module. pModule = PyImport_Import(pName); // Create a dictionary for the contents of the module. pDict = PyModule_GetDict(pModule); // Get the add method from the dictionary. pFunc = PyDict_GetItemString(pDict, "add"); // Create a Python tuple to hold the arguments to the method. pArgs = PyTuple_New(2); // Convert 2 to a Python integer. pValue = PyLong_FromLong(2); // Set the Python int as the first and second arguments to the method. PyTuple_SetItem(pArgs, 0, pValue); PyTuple_SetItem(pArgs, 1, pValue); // Call the function with the arguments. PyObject* pResult = PyObject_CallObject(pFunc, pArgs); // Print a message if calling the method failed. if(pResult == NULL) printf("Calling the add method failed.\n"); // Convert the result to a long from a Python object. long result = PyLong_AsLong(pResult); // Destroy the Python interpreter. Py_Finalize(); // Print the result. printf("The result is %d.\n", result); //std::cin.ignore(); return 0; }
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
- (void)helloWorld { printf("Calling Python to find the sum of 2 and 2.\n"); NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; PyObject *sys_path = PySys_GetObject("path"); PyList_Append(sys_path, PyUnicode_FromString([resourcePath UTF8String])); // Special environment to avoid writing bytecode because // the process will not have write attribute on the device. putenv("PYTHONDONTWRITEBYTECODE=1"); NSString *python_home = [NSString stringWithFormat:@"%@/Library/Python.framework/Resources", resourcePath, nil]; NSLog(@"PythonHome is: %@", python_home); wchar_t *wpython_home = Py_DecodeLocale([python_home UTF8String], NULL); Py_SetPythonHome(wpython_home); // iOS provides a specific directory for temp files. NSString *tmp_path = [NSString stringWithFormat:@"TMP=%@/tmp", resourcePath, nil]; putenv((char *)[tmp_path UTF8String]); // Initialize the Python interpreter. Py_Initialize(); // Create some Python objects that will later be assigned values. PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; // Convert the file name to a Python string. pName = PyUnicode_FromString("sample"); // Import the file as a Python module. pModule = PyImport_Import(pName); // Create a dictionary for the contents of the module. pDict = PyModule_GetDict(pModule); // Get the add method from the dictionary. pFunc = PyDict_GetItemString(pDict, "add"); // Create a Python tuple to hold the arguments to the method. pArgs = PyTuple_New(2); // Convert 2 to a Python integer. pValue = PyLong_FromLong(2); // Set the Python int as the first and second arguments to the method. PyTuple_SetItem(pArgs, 0, pValue); PyTuple_SetItem(pArgs, 1, pValue); // Call the function with the arguments. PyObject* pResult = PyObject_CallObject(pFunc, pArgs); // Print a message if calling the method failed. if(pResult == NULL) printf("Calling the add method failed.\n"); // Convert the result to a long from a Python object. long result = PyLong_AsLong(pResult); // Destroy the Python interpreter. Py_Finalize(); // Print the result. printf("The result is %d.\n", result); }
Subscribe to:
Posts (Atom)