Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell output not being fully retrieved by PHP!

I have a PHP script which executes a shell command:

$handle = popen('python last', 'r');
$read = fread($handle, 4096);
print_r($read);
pclose($handle);

I echo the output of the shell output. When I run this in the command I get something like this:

[root@localhost tester]# python last
[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[last] ZVZX-W3vo9I: URL: x
[download] Destination: here.flv
[download]   0.0% of 10.09M at     ---b/s ETA --:--
[download]   0.0% of 10.09M at   22.24k/s ETA 07:44
[download]   0.0% of 10.09M at   66.52k/s ETA 02:35
[download]   0.1% of 10.09M at  154.49k/s ETA 01:06
[download]   0.1% of 10.09M at  162.45k/s ETA 01:03

However, when I run that same command from PHP I get this output:

[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[last] ZVZX-W3vo9I: URL: x
[download] Destination: here.flv

As you can see the bottom bit is missing which is the bit I need!! The problem before was that the percentages were being updated on the same line but now I have changed my Python script so that it creates a new line. But this made difference! :(

This question is related to this one.

Thank you for any help.

Update

Needed to redirect output "2>&1". Arul got lucky :P since I missed the deadline to pick the one true answer which belonged to Pax!

like image 253
Abs Avatar asked Nov 27 '22 21:11

Abs


1 Answers

You read only the first 4,096 bytes from the pipe, you'll need to place the fread/print_r in a loop and check for the end-of-file using the feof function.

$handle = popen('python last', 'r');

while(!feof($handle))
{
    print_r(fread($handle, 4096));
} 

pclose($handle);
like image 126
arul Avatar answered Jan 05 '23 20:01

arul