Communication between two python scripts

methodological issue:

I have a β€œmain” python script that runs in an infinite loop on my system, and I want to send it information (for example, a json data string), sometimes with some other python scripts that will be launched later on their own or by another program and will end right away after sending the line.

I cannot use the subprocess here because my main script does not know when the other will work and what code they will execute.

I am thinking of doing a main script listening on a local port and forcing other scripts to send strings to it on that port, but is there a better way to do this?

+7
source share
3 answers

zeromq: http://www.zeromq.org/ is the best imho interprocess communication solution and has excellent python bindings: http://www.zeromq.org/bindings:python

+10
source

Since the β€œmain” script is similar to a service, you can improve it using the web API. bottle is the perfect solution for this. With this extra code, your python script will be able to receive requests and process them:

import json from bottle import run, post, request, response @post('/process') def my_process(): req_obj = json.loads(request.body.read()) # do something with req_obj # ... return 'All done' run(host='localhost', port=8080, debug=True) 

The client script can use httplib to send a message to the server and read the response:

 import httplib c = httplib.HTTPConnection('localhost', 8080) c.request('POST', '/process', '{}') doc = c.getresponse().read() print doc # 'All done' 
+4
source

If you are interested in implementing the client script that Mike introduced in Python 3.x, you will quickly find that there is no httplib available. Fortunately, the same thing happens with the http.client library.

Otherwise, it is one and the same:

 import http c = http.client.HTTPConnection('localhost': 8080) c.request('POST', '/process', '{}') doc = c.getresponse().read() print(doc) 

Although this is old, I would have thought that I would publish it, because today I had a similar question, but using a server.

+1
source

All Articles