How to output the data incrementally from a ajax request when php executes a python script with variables? The below code output all the data on completion, my actual python script is large and can take over 10 minutes to complete. I like to see the printed status message embedded into the script. Or is there a is a better way then what I’m trying to attempt.
Solution Found I need to add 'sys.stdout.flush()' after each print request in python. Thank you to Sander Marechal!
$('#config_form').on('click', '.config-button', function () {
var dataString = 'mystring1="test1"' +
'&mystring2="test2"' ;
$.ajax({
type: "POST",
url: "./php/pyhon_test.php",
data: dataString,
cache: false,
xhrFields: {
onprogress: function(e) {
console.log(e.target.responseText)
}
}
});
return false;
});
PHP
<?php
session_start();
session_write_close();
$mystring1 = $_POST["mystring1"];
$mystring2 = $_POST["mystring2"];
$a = popen("/bin/python3.9 /var/www/html/cps/dops/python/python_script.py $mystring1 $mystring2 2>&1", "r");
while($b = fgets($a, 2048)) {
echo $b;
ob_flush();flush();
}
pclose($a);
// Slow output progression to console.log
$x = 1;
while($x <= 5) {
sleep(5);
echo "pass-".$x."\r\n";
flush();
ob_flush();
$x++;
}
session_destroy();
?>
Python
import sys
import time
myvar1 = sys.argv[1]
myvar2 = sys.argv[2]
print(myvar1+"-a")
sys.stdout.flush()
time.sleep(2)
print(myvar2+"-b")
sys.stdout.flush()
time.sleep(2)
print(myvar1+"-c")
sys.stdout.flush()
time.sleep(2)
print(myvar2+"-d")
sys.stdout.flush()
time.sleep(2)
print(myvar1+"-e")
sys.stdout.flush()
time.sleep(2)
print(myvar2+"-f")
sys.stdout.flush()
time.sleep(2)
Console Log
console.log output loop 1.
true-contain
test1-a
test2-b
test1-c
test2-d
test1-e
test2-f
false
console.log output loop 2.
pass-1
pass-2
pass-3
pass-4
pass-5