我如何在php中嵌入python脚本? [英] How I embed a python script in php?
本文介绍了我如何在php中嵌入python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在StackOverflow上也有类似的问题,但是我已经尝试了所有这些问题,但没有一个起作用.在我的笔记本电脑上,我有一个Apache服务器,一个使用PHP和Python脚本构建的网站.
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.
尝试:
1)系统
$mystring = system('python myscript.py myargs', $retval);
2)和3) JSON 和$ temp = exec($ command,$ output);
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配置:
4) apache configuration is setted:
AddHandler cgi-script .cgi .py
推荐答案
exec()对我来说很好.
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!
)
那是在交互式控制台中的,这只是纯PHP:
That was in the interactive console, here's just the pure php:
$output = exec('python myscript.py', $output);
print_r(json_decode($output));
这篇关于我如何在php中嵌入python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文