我的问题可能不正确,甚至很奇怪,但我对这种编程经验真的很感兴趣,原因有两个:
作为一名 PHP 开发人员,我应该做好自己的工作,这样我就不能那么容易地切换到其他编程语言;然而,有很多事情导致用 PHP 编写很痛苦。
里>
例如,我一直在用 PHP 编写一个广播多连接套接字服务器,任何做过类似事情的人都会明白有多少限制会导致这种解决方案 - 如果客户端刚刚关闭浏览器则检测断开连接是可怕的。查看 Python 中的广播服务器实现让我感觉更舒服。
此外,考虑一下可以在离线模式下工作的应用程序,以收集用户输入并稍后将其发送到处理服务器,或者连接到网站的独立应用程序等。
在这种情况下,网络搜索效果很差。我找到的只是 PiP ,但它发布得太久了,而且没有很好的记录 - 这可能是有充分理由的。
我很高兴听到对此的任何想法,因为我知道这个想法有点疯狂,而且看起来没有很多人关心它。
最佳答案
前段时间我也遇到过类似的困境。我找到的解决方案是使用 xml-rpc 公开 python 对象和方法,以便我可以从 php 脚本中使用它们。我在这里给您留下了两者的文档。
Python:Python xml-rpc. PHP:XML-PHP
编辑:添加示例。这些示例与文档中的示例相同。我只是对它们做了一些修改,让它们变得更短。在 client.php
中,我仅从 python 服务器调用 div
函数。将其他人添加为您自己。
server.py
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x,y):
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
def div(self, x, y):
return x // y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
client.php
<html>
<head><title>xmlrpc</title></head>
<body>
<h1>Php - Python - XMLRPC Demo</h1>
<?php
// Note that the path to xmlrpc.inc file is relative.
// to this file.
include("xmlrpc/lib/xmlrpc.inc");
// Params to python function 10 and 5.
// Build the message you want send.
// The message takes the function name and the params. See doc for details on how
// build params, is pretty easy.
$msg = new xmlrpcmsg( "div", array(new xmlrpcval(10, "int"), new xmlrpcval(5, "int")) );
// Build a XMLRCP - Client.
$client = new xmlrpc_client("/RPC2", "localhost", 8000);
// And send the message.
$response = $client->send($msg);
// From here all should look familier to you.
if(!$response->faultCode())
{
$v=$response->value();
echo "The result from div is" . htmlspecialchars($v->scalarval());
}
else
{
print "An error occurred: ";
print "Code: " . htmlspecialchars($r->faultCode())
. " Reason: '" . htmlspecialchars($r->faultString()) . "'</pre><br/>";
}
?>
<hr/>
</body>
</html>
关于与Python模块结合的PHP脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21054234/