从PHP发送数据到Python脚本

Jak*_*ans 1 php python sockets

这是我的问题,我有一个Python脚本将在while(1)循环中无限期运行.我想要一些PHP脚本以某种方式与Python脚本交互,当它发生时,脚本需要使用提交给脚本的数据执行一个函数.

任何想法,将不胜感激!

ndp*_*dpu 5

您可以使用redis(例如pub/sub功能)作为进程间通信工具.

Redis是一个开源(BSD许可),内存数据结构存储,用作数据库,缓存和消息代理.它支持数据结构,如字符串,散列,列表,集合,带有范围查询的排序集,位图,超级日志和带有半径查询的地理空间索引.Redis具有内置复制,Lua脚本,LRU驱逐,事务和不同级别的磁盘持久性,并通过Redis Sentinel提供高可用性并使用Redis Cluster自动分区.

除了通过redis的IPC,你可以使用它作为分布式键值数据库 - redis imho的巨大优势.

另一种选择 - zeromq - 用于进程间通信的最着名工具之一.互联网上有很多关于它的教程和文档.原始指南:http://zguide.zeromq.org/page:all

ØMQ(也称为ZeroMQ,0MQ或zmq)看起来像一个可嵌入的网络库,但就像一个并发框架.它为您提供了在各种传输中传输原子消息的套接字,如进程内,进程间,TCP和多播.您可以使用扇出,发布 - 订阅,任务分发和请求 - 回复等模式连接N到N的套接字.它足够快,可以成为集群产品的结构.其异步I/O模型为您提供可扩展的多核应用程序,构建为异步消息处理任务.它有许多语言API,可在大多数操作系统上运行.ØMQ来自iMatix,是LGPLv3的开源软件.

python上的Hello world服务器和客户端:https://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/patterns/client_server.html

官方指南中PHP服务器和python客户端的简单示例:

PHP服务器:

<?php
/*
*  Hello World server
*  Binds REP socket to tcp://*:5555
*  Expects "Hello" from client, replies with "World"
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/

$context = new ZMQContext(1);

//  Socket to talk to clients
$responder = new ZMQSocket($context, ZMQ::SOCKET_REP);
$responder->bind("tcp://*:5555");

while (true) {
    //  Wait for next request from client
    $request = $responder->recv();
    printf ("Received request: [%s]\n", $request);

    //  Do some 'work'
    sleep (1);

    //  Send reply back to client
    $responder->send("World");
}
Run Code Online (Sandbox Code Playgroud)

Python中的Hello World客户端:

#
#   Hello World client in Python
#   Connects REQ socket to tcp://localhost:5555
#   Sends "Hello" to server, expects "World" back
#
import zmq

context = zmq.Context()

#  Socket to talk to server
print "Connecting to hello world server…"
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")

#  Do 10 requests, waiting each time for a response
for request in range(10):
    print "Sending request %s …" % request
    socket.send("Hello")

    #  Get the reply.
    message = socket.recv()
    print "Received reply %s [ %s ]" % (request, message)
Run Code Online (Sandbox Code Playgroud)