Skip to content
Advertisement

Can’t output Python Print in PHP

I’m really stuck on this one, but I am a python (and Raspberry Pi) newbie. All I want is to output the print output from my python script. The problem is (I believe) that a function in my python script takes half a second to execute and PHP misses the output.

This is my php script:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$cmd = escapeshellcmd('/var/www/html/weathertest.py');
$output = shell_exec($cmd);
echo $output;

//$handle = popen('/var/www/html/weathertest.py', 'r');
//$output = fread($handle, 1024);
//var_dump($output);
//pclose($handle);

//$cmd = "python /var/www/html/weathertest.py";
//$var1 = system($cmd);
//echo $var1;

echo 'end';
?>

I’ve included the commented blocks to show what else I’ve tried. All three output “static text end”

This is the python script:

#!/usr/bin/env python

import sys
import Adafruit_DHT
import time

print 'static text '

humidity, temperature = Adafruit_DHT.read(11, 4)

time.sleep(3)

print 'Temp: {0:0.1f}C Humidity: {1:0.1f}%'.format(temperature, humidity)

The py executes fine on the command line. I’ve added the 3 second delay to make the script feel longer for my own testing.

Given that I always get static text as an output, I figure my problem is with PHP not waiting for the Adafruit command. BUT the STRANGEST thing for me is that all three of my PHP attempts work correctly if I execute the PHP script on the command line i.e. php /var/www/html/test.php – I then get the desired output:

static text
Temp: 23.0C Humidity 34.0%
end

So I guess there’s two questions: 1. How to make PHP wait for Python completion. 2. Why does the PHP command line differ from the browser?

Advertisement

Answer

  1. How to make PHP wait for Python completion

shell_exec will wait the command to finish

  1. Why does the PHP command line differ from the browser?

My best guess is the difference of the user running the command. On the command line the script is running as the same user you’re logged in, on the “browser”, probably as the same user as apache/nginx, the environment variables are different on both cases.


Add python before the script, i.e.:

$output = shell_exec("python /var/www/html/weathertest.py");
echo $output;

Or use the fullpath to the python binary:

$output = shell_exec("/full/path/to/python /var/www/html/weathertest.py");
echo $output;

PS: To know the fullpath use which python on the shell.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement