在XAMPP中使用shell_exec()从PHP调用Python



我正在尝试在XAMPP上工作。它在Linux服务器/虚拟机上运行良好。我需要向python脚本发送一个关联数组,我使用:

<?php
echo "Test simple call/answer process<br>";
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$param = base64_encode(json_encode($age));
$command = escapeshellcmd('python python_array_answer.py $param');
$output = shell_exec($command);
$obj = json_decode($output);
print_r($obj);
?>

Python脚本是:

#! /Users/.../AppData/Local/Programs/Python/Python37/python.exe
import sys
import json
import base64
hotel_data = json.loads(base64.b64decode(sys.argv[1]))
print(json.dumps(hotel_data))

我得到一个NULL数组返回,有这个错误:

Traceback (most recent call last):
File "python_array_answer.py", line 6, in <module>
hotel_data = json.loads(base64.b64decode(sys.argv[1]))
File "C:UsersmghigliaAppDataLocalProgramsPythonPython37libbase64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4
Any ideas? thank.

假设其余代码没有问题,则在这一行使用单引号

$command = escapeshellcmd('python python_array_answer.py $param');

,你应该使用双引号,这样PHP就知道用变量$param的值替换$param,或者像这样将两者连接起来…

$command = escapeshellcmd('python python_array_answer.py '.$param);

最新更新