【问题标题】:How I embed a python script in php?如何在 php 中嵌入 python 脚本?
【发布时间】:2013-06-26 23:50:24
【问题描述】:

我知道 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);

蟒蛇:

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 

【问题讨论】:

    标签: php python interface


    【解决方案1】:

    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));
    

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多