Hello I want to run python script from php. Python script is for reading sensor data. This is python code and it's file name is sensor.py

import bluetooth
bd_addr="(mac address)"
while 1:
    data +=sock.recv(1024)
    if data_end !=-1:
      rec data_end[:data_end]
      print data
  except Keyboard Interrupt

Now I can read sensor data if I run sensor.py and I want to display sensor data on web server from php without database.

So I save php file in /var/www/html folder. It is code of file and file name is server.php

$output=shell_exec('python /home/pi/sensor.py');
echo "<pre>$output</pre>";

And I insert localhost/server.php on web browser but I can't check sensor data because of HTTP 500 ERROR. I thought it is because of permission. So I save another php file in /var/www/html to check my permission and it's file name is test.php

echo "HI";
echo date('y-m-d- H:i:s);

And I insert localhost/test.php I can check HI and date. Then why I can't check sensor data if I insert localhost/sensor.php ?


No, this is because your python script has an endless loop. Web servers impose a runtime limit on started scripts, most times in the range of seconds. The PHP interpreter itself has another limit.

You have to make your python script return within that timeframe. If you want to pass values to the browser window of the user continously, you have to run a Javascript in the browser which continously reloads a dedicated data page from the server. That way, the loop runs inside the browser and all is fine.

Also, there are no keyboard interrupts in a background process.

  • You might also want to note in your answer that PHP has a configurable time limit which might be the cause of the timeout and that it can be changed programmatically. – Aurora0001 Mar 11 '18 at 9:47
  • 1
    I've edited my answer. – Janka Mar 11 '18 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.