两个python脚本之间的通信
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16213235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Communication between two python scripts
提问by Dettorer
a methodology question:
一个方法论问题:
I have a "main" python script which runs on an infinite loop on my system, and I want to send information to it (a json data string for example) occasionally with some other python scripts that will be started later by myself or another program and will end just after sending the string.
我有一个“主”python 脚本,它在我的系统上无限循环运行,我想偶尔向它发送信息(例如一个 json 数据字符串),以及一些其他的 python 脚本,这些脚本稍后将由我自己或其他程序启动并将在发送字符串后结束。
I can't use subprocess here because my main script doesn't know when the other will run and what code they will execute.
我不能在这里使用子进程,因为我的主脚本不知道另一个何时运行以及它们将执行什么代码。
I'm thinking of making the main script listen on a local port and making the other scripts send it the strings on that port, but is there a better way to do it ?
我正在考虑让主脚本侦听本地端口并使其他脚本在该端口上向它发送字符串,但是有没有更好的方法来做到这一点?
采纳答案by Vladimir Muzhilov
zeromq: http://www.zeromq.org/- is best solution for interprocess communications imho and have a excelent binding for python: http://www.zeromq.org/bindings:python
zeromq:http://www.zeromq.org/-是最好的解决方案,进程间通信恕我直言,有一个外观极好的Python绑定:http://www.zeromq.org/bindings:python
回答by mike
Since the "main" script looks like a service you can enhance it with a web API. bottleis the perfect solution for this. With this additional code your python script is able to receive requests and process them:
由于“主”脚本看起来像一项服务,因此您可以使用 Web API 对其进行增强。瓶子是这个的完美解决方案。使用此附加代码,您的 python 脚本能够接收请求并处理它们:
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 may use the httplib to send a message to the server and read the response:
客户端脚本可以使用 httplib 向服务器发送消息并读取响应:
import httplib
c = httplib.HTTPConnection('localhost', 8080)
c.request('POST', '/process', '{}')
doc = c.getresponse().read()
print doc
# 'All done'
回答by Bradley Robinson
In case you are interested in implementing the client script that Mike presented in Python 3.x, you will quickly find that there is no httplib available. Fortunately, the same thing is done with the library http.client.
如果您对实现 Mike 在 Python 3.x 中提供的客户端脚本感兴趣,您会很快发现没有可用的 httplib。幸运的是,库 http.client 也做了同样的事情。
Otherwise it is the same:
否则是一样的:
import http.client
c = http.client.HTTPConnection('localhost', 8080)
c.request('POST', '/process', '{}')
doc = c.getresponse().read()
print(doc)
Though this is old I would figure I would post this since I had a similar question today but using a server.
虽然这是旧的,但我想我会发布这个,因为我今天有一个类似的问题,但使用的是服务器。

