简体   繁体   中英

PHP display Python in real-time

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!

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM