gpt4 book ai didi

结合 Python 模块的 PHP 脚本

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:30 25 4
gpt4 key购买 nike

我的问题可能不正确甚至很奇怪,但我真的对这样的编程经验很感兴趣,原因有两个:

  1. 作为一名 PHP 开发人员,我应该做好自己的工作,这样我就不能那么容易地切换到其他编程语言;但是,有很多东西会导致用 PHP 编写时很痛苦。

  2. 作为 Python 初学者,我已经是这门语言的 super 粉丝,有些事情可以更轻松地完成,恕我直言,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com