How I embed a python script in php?

我怕爱的太早我们不能终老 提交于 2021-02-04 14:17:27

问题


I know that there are similar questions on StackOverflow but I've tried all of them and none of them worked. On my laptop, I have an Apache server, a website built with PHP and a Python script.

Attempts:

1) system

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

2) and 3) JSON and $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 configuration is setted:

AddHandler cgi-script .cgi .py 

回答1:


exec() worked just fine for me.

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

That was in the interactive console, here's just the pure php:

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


来源:https://stackoverflow.com/questions/17332319/how-i-embed-a-python-script-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!