1

I'm trying to get a simple Python script to output to PHP in real-time, and I find myself having trouble to accomplish it.

The script is nothing fancy, for testing purposes, just this:

#!/usr/bin/python
import time

time.sleep(1)
print "message 1"
time.sleep(1)
print "message 2"
time.sleep(1)
print "message 3"
time.sleep(1)
print "message 4"

I've tried calling the Python code several ways. It seems when I try to run it from:

<?php
$output=shell_exec("/var/www/html/output.py");
print_r($output);
?>

It seems to wait for 4 secondes, and outputs the entire thing.

I've tried messing around with the ob_flush and flush() PHP commands, but I'm not able to get the effect that I want, it's essentually the same as the shell_exec()

And input would be greatly appreciated!

user5740843
  • 1,540
  • 5
  • 22
  • 42
  • 1
    Possible duplicate of [Running a Python script from PHP](http://stackoverflow.com/questions/19735250/running-a-python-script-from-php) – Hendra Nucleo Apr 21 '16 at 14:39
  • 1
    Possible duplicate of [Run process with realtime output in PHP](http://stackoverflow.com/questions/1281140/run-process-with-realtime-output-in-php) – Cyrbil Apr 21 '16 at 14:46

1 Answers1

0

You should probaby use the passthru() function for what you want.

This is already answered in this SO Answer by Niklas Lindblad: https://stackoverflow.com/a/19736525/488191

I recommend using passthru and handling the output buffer directly:

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean();
Community
  • 1
  • 1
ssice
  • 3,564
  • 1
  • 26
  • 44