php - 如何在 php 中嵌入 python 脚本?

标签 php python interface

我知道 StackOverflow 上有类似的问题,但我已经尝试了所有这些问题,但没有一个起作用。在我的笔记本电脑上,我有一个 Apache 服务器、一个用 PHP 和 Python 脚本构建的网站。

尝试:

1) system

$mystring = system('python myscript.py myargs', $retval); 

2) 和 3) JSON和 $temp = exec($command, $output);

php:

#first case
command= 'C:\wamp\www\com\non.py file';
$temp = exec($command, $output);
echo(" output ");

echo $output;
echo " hello ";
echo $temp;

#second case
// Execute the python script with the JSON data
$result = shell_exec('python /confronto/non.py '); 
#. escapeshellarg(json_encode($data)));

// Decode the result
$resultData = json_decode($result, true);

// This will contain: array('status' => 'Yes!')
var_dump($resultData);

python :

import sys, json

def tests():
    b = 2
    print("inside test")
    print(b)
    a = 4
    return a

#if __name__ == "__main__":

c = tests()
print("main")
print(c)
# Generate some data to send to PHP
result = {'status': 'Yes!'}

# Send it to stdout (to PHP)
print json.dumps(result)

4)apache配置设置:

AddHandler cgi-script .cgi .py 

最佳答案

exec() 对我来说效果很好。

murftown$ php -a
Interactive shell

php > $output = exec('python myscript.py', $output);
php > echo $output;
{"status": "Yes!"}
php > print_r(json_decode($output));
stdClass Object
(
    [status] => Yes!
)

那是在交互式控制台中,这里只是纯 php:

$output = exec('python myscript.py', $output);
print_r(json_decode($output));

关于php - 如何在 php 中嵌入 python 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17332319/

相关文章:

perl - 使用类::接口(interface)

java - 银行类OOP接口(interface)决定

php - 在同一个 mysql 表上组合多个查询

php - 通过 PHP 将 json 格式化为 geojson

php - php 5.6 + 中的 mysql_connect

c# - 为什么有些结构继承接口(interface),但不实现其所有成员?

php - 高效的php/mysql查询在php中生成html表

python - 如何匹配2个字符串列表?

python按钮点击后更改文本

python - 线性回归预测的非常大的值