问题
I am a Noob with the raspberry pi. I have it all setup and I am trying to run a file via the browser using shell_exec
.
Here is the content of the python file:
#! /usr/bin/python
import time
import RPi.GPIO as GPIO
PIN_17 = 17 # Define LED colour and their GPIO pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_17, GPIO.OUT) # Setup GPIO pin
GPIO.output(PIN_17, True) #Turn on
time.sleep (1) #Wait
GPIO.output(PIN_17, False) #Turn off
GPIO.cleanup() #Useful to clear the board
I have the file in the directory /home/pi/
called trigger_pin.py
I am trying to run the file through the browser using the PHP command below in remote.php
:
<?php
$output = shell_exec("cd /home/pi/ && ./trigger_pin.py 2>&1"); //run command
echo "$output"; //output from command
?>
The output I am getting is:
Traceback (most recent call last): File "./trigger_pin.py", line 9, in GPIO.setup(PIN_17, GPIO.OUT) # Setup GPIO pin RuntimeError: No access to /dev/mem. Try running as root!
回答1:
By default, the Raspberry Pi's GPIO interface requires superuser ("root") permissions. You may have a root-user shell open, therefore executing your Python script works without issues from the command line. Whereas, your PHP application server is likely running as another user.
The most straight-forward solution is to add the PHP application server's user (e.g., www-data
) to /etc/sudoers
, which will create a privileged user.
www-data ALL = NOPASSWD: ALL
And then escalate your permissions with sudo
:
shell_exec("cd /home/pi/ && sudo ./trigger_pin.py 2>&1");
If you do this, be absolutely certain you verify the safety of what your Web server can execute (i.e., don't blindly install Web scripts with reviewing the source code).
Alternatively, you can refactor your Python script to use pigpio's pigpiod
daemon, which runs with superuser privileges (so your application doesn't have to). Or you can use a separate tool that uses setuid
to run as root such as Quick2Wire's GPIO Admin.
You can also find more help at Raspberry Pi Stack Exchange.
回答2:
Use this command
$ sudo python filename.py
来源:https://stackoverflow.com/questions/27864804/no-access-to-dev-mem-try-running-as-root-on-raspberry-pi