在PHP中执行Python

4 投票
4 回答
20475 浏览
提问于 2025-04-16 23:28

假设你有一个这样的类:

class MyClass:
    def __init__(self, var1):
        self.var = var1
    ....

这个类在Python中,只有在你给它赋值的时候才会工作:

x = MyClass("Hi")

所以,我的问题是,我能不能从PHP发送一个变量去执行这个Python类,并且把它的输出(是个字符串)返回过来,然后继续执行我的PHP代码?

有什么建议吗?

解决方案

在PHP中:

$var = "something";
$result = exec("python fileName.py .$var")

在Python中:

import sys

sys.argv[0] # this is the file name
sys.argv[1] # this is the variable passed from php

4 个回答

0

我写了一个简单的函数 PY(),可以让你在 PHP 脚本里几乎像是包含 Python 代码一样使用它。你还可以把一些输入变量传给 Python 进程。不过,你不能把数据从 Python 返回到 PHP,但我觉得这个问题应该不难解决 :)

这个方法不太适合在网络托管上使用(因为可能不安全,涉及到 system() 调用),我主要是为 PHP-CLI 创建的,但在其他地方也可能能正常工作。

<?php

function PY()
{
 $p=func_get_args();
 $code=array_pop($p);
 if (count($p) % 2==1) return false;
 $precode='';
 for ($i=0;$i<count($p);$i+=2) $precode.=$p[$i]." = json.loads('".json_encode($p[$i+1])."')\n";
 $pyt=tempnam('/tmp','pyt');
 file_put_contents($pyt,"import json\n".$precode.$code);
 system("python {$pyt}");
 unlink($pyt);
}

//begin
echo "This is PHP code\n";
$r=array('hovinko','ruka',6);
$s=6;

PY('r',$r,'s',$s,<<<ENDPYTHON
 print('This is python 3.4 code. Looks like included in PHP :)');
 s=s+42
 print(r,' : ',s)
ENDPYTHON
); 
echo "This is PHP code again\n";
?>
0

可以试试Python的PECL包:

这个扩展让Python解释器可以嵌入到PHP里面,这样你就可以在PHP中创建和操作Python对象了。

http://pecl.php.net/package/python

7

首先,创建一个文件,里面写上你想要执行的Python脚本,包括(或者加载)你定义的类,以及这行代码 x = MyClass("Hi")

接下来,使用下面这一行代码来获取结果:

$result = exec('python yourscript.py');

撰写回答