我知道 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/