从PHP执行Python脚本 [英] Execute Python script from Php

查看:1427
本文介绍了从PHP执行Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的2个按钮树莓派一个PHP网页(或关闭)
ON按钮按钮重定向到On.php
OFF按钮重定向到Off.php
在/ usr / lib目录/ cgi-bin目录我有一个Python脚本,我想执行(script.py)
我完全可以从终端通过键入执行它

I have a PHP webpage on my raspberry pi with 2 buttons (on and off) The on button button redirects to On.php The off button redirects to Off.php In "/usr/lib/cgi-bin" I have a python script that I would like to execute (script.py) I can perfectly execute it from the terminal by typing

cd /usr/lib/cgi-bin
sudo python script.py

它的工作原理,如果我这样做从终端。

It works if I do it from the terminal.

问题是在我的的/ var / www的文件夹中的PHP文件(On.php)。
这是我写的:

The problem is the PHP file (On.php) in my "/var/www" folder. This is what I wrote:

<?php
exec('cd /usr/lib/cgi-bin');
exec('sudo python script.py');
?>

为什么脚本从终端执行,而不是从我的PHP?

Why is the script executing from the terminal, but not from my PHP?

推荐答案

您不能从PHP脚本使用sudo。 Apache是​​从用户(www数据generaly)运行,因此编辑这个文件:的/ etc / sudoers文件

You can't use sudo from a PHP script. Apache is running from an user (www-data generaly), so edit this file : /etc/sudoers

然后加入这一行:

www-data ALL=(ALL) NOPASSWD:ALL

护理!这将授权所有功能由一个PHP脚本调用,可以适应不断变化的ALL的脚本或Python命令。

Care ! this will authorize all functions to be called by a PHP script, you can adapt changing "ALL" by your script or Python command.

然后precise你的用户在你的exec命令:

Then precise your user in your exec command :

<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/script.py')

这篇关于从PHP执行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆