在PHP中执行python脚本


Exectute python script in PHP

我使用的是API,它在执行python脚本时会创建一个JSON文件,所以我尝试使用exec来运行python脚本并检索JSON。然而,python脚本似乎没有执行。我做错了什么?我正在使用MAMP 在apache上尝试

exec('python http://localhost:8888/examples/recent_matches_to_json.py');

$json =     file_get_contents('http://localhost:8888/examples/recent_matches.json');
$obj = json_decode($json);
var_dump($obj->recent, true);

嗯。。。你应该下载脚本并保存它,然后在上面运行解释器

类似于:

$py_script = file_get_contents('http://localhost:8888/examples/recent_matches_to_json.py');
file_put_contents('recent_matches_to_json.py', $py_script);
exec('python recent_matches_to_json.py');

如果您打算从本地计算机下载脚本,为什么不直接运行它呢?像exec('python /home/peter/site/examples/recent_matches_to_json.py')

您还可以在Python脚本中设置一个web/WSGI服务器,这样您就可以通过发送HTTP请求(如http://localhost:9999/recent_matches_to_json/)直接运行它。