14

I've recently setup python to work with lighttpd via CGI (see here). But the minute I go to include RPi.GPIO, the script stops executing (I'm assuming because no HTML gets output), but there is no error output into the error log (/var/log/lighttpd/error.log).

gpio.py

import RPi.GPIO as GPIO

print "<html>"
print "\t<head>"
print "\t\t<title>GPIO</title>"
print "\t</head>"
print "\t<body>"
print "\t\t<p>"
print "\t\t\tGPIO #17 status: "
print "\t\t</p>"
print "\t</body>"
print "</html>"

Why is the script not executing? Is it because of permissions? Surely, including the library shouldn't require any special permissions? Why isn't there any error output either in the script or in the error log?

Mark Ingram
  • 889
  • 3
  • 11
  • 18

4 Answers4

6

You may try to add before 'import RPi.GPIO':

import sys 
sys.stderr = sys.stdout
try:
    import RPi.GPIO as GPIO
except Exception as e:
    print e

It may help to diagnose an error.

And add these lines before your html output:

print "Content-Type: text/html"     # HTML is following
print                               # blank line, end of headers

See http://docs.python.org/library/cgi.html

Alex Chamberlain
  • 15,638
  • 15
  • 69
  • 113
okertanov
  • 609
  • 4
  • 2
6

After following the advice from okertanov, I discovered that you can't actually use RPi.GPIO in a python CGI script as it requires root access. I worked around the problem by calling out to the gpio command line app which is included as part of WiringPi, this can be called from a non-root account.

# Read the GPIO pin using the gpio application

import subprocess as s

def ReadGpio(pin) :
    process = s.Popen(["/usr/local/bin/gpio", "-g", "read", pin], stdout = s.PIPE)
    data, _ = process.communicate()

    data = str.replace(data, “\r”, “”)
    data = str.replace(data, “\n”, “”)

    return data
Mark Ingram
  • 889
  • 3
  • 11
  • 18
0

# means a comment in Python

Just use

import RPi.GPIO as GPIO

Now you'll need to solve the permissions problem

John La Rooy
  • 12,005
  • 9
  • 48
  • 77
0

This tutorial recommends creating a special copy of Python and giving it root user privileges, like so:

//check current version
pi@raspberrypi /var/www $ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 9 Jun  6  2012 /usr/bin/python -> python2.7

//copy and chmod
pi@raspberrypi /var/www $ sudo cp /usr/bin/python2.7 /usr/bin/pythonRoot
pi@raspberrypi /var/www $ sudo chmod u+s /usr/bin/pythonRoot

//check that new version has more priveledges
pi@raspberrypi /var/www $ ls -l /usr/bin/pythonRoot
-rwsr-xr-x 1 root root 2674528 Mar 17 18:16 /usr/bin/pythonRoot

And then, to make your CGI, go to sudo nano /etc/lighttpd/lighttpd.conf and find wherever it is you are directing .py files from and change /usr/bin/python/ to the new /usr/bin/pythonRoot/

Seph Reed
  • 327
  • 1
  • 6
  • 18