AJAX Progress: Reading output from the Shell

2019-04-02 08:56发布

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

3条回答
手持菜刀,她持情操
2楼-- · 2019-04-02 09:27

Are you reading until EOF?

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

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

pclose($handle);
查看更多
在下西门庆
3楼-- · 2019-04-02 09:32

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.

查看更多
欢心
4楼-- · 2019-04-02 09:48

This will be your friend:

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

Further info can be found here: Wikipedia

查看更多
登录 后发表回答