AJAX Progress: Reading output from the Shell

2019-04-02 08:46发布

问题:

Objective: Make a progress bar where users can check how much of a file has been downloaded by my server.

Scenario:I have a PHP script that executes a python script via popen. I have done this like so:

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

$read = fread($handle, 4096);

pclose($handle);

This python script outputs to the shell something like this:

[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[download] Destination: myvideo.flv
[download]   9.9% of 10.09M at    3.30M/s ETA 00:02

Problem:When I read in the file generated by the shell output I get all the shell output except the last line!? WHY?

Just to add, when I run the command via the shell, the shell cursor appears at the end of that line and waits till the script is done.

Thanks all

回答1:

First thing that comes into my mind: maybe the program detects that it is not executed on a TTY and therefore does not show the last line, which probably involves ugly control characters because that line seems to update itself?

What happens when you redirect the output to a file (in the shell), or pipe it through less? If you don't see the last line there, this is likely to be the case. I don't know of another solution than to fix the source.



回答2:

Are you reading until EOF?

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

while (!feof($handle)) {
  $read .= fread($handle, 4096);
}

pclose($handle);


回答3:

This will be your friend:

$handle = popen('python last 2>&1', 'r');

Further info can be found here: Wikipedia