执行“少”从命令行PHP w /滚动 [英] Execute "less" from command-line PHP w/ Scrolling
问题描述
我想从PHP中的命令行执行更少
和类似程序。
I want to execute less
and similar programs from the command-line in PHP.
通常的嫌疑犯(exec,shell_exec,passthru等),并且虽然他们中的许多可以将文件转储到屏幕,该进程在我可以使用它之前终止。如果我想要 cat
,我会使用它。
I have tried the usual suspects (exec, shell_exec, passthru, etc), and while many of them can dump the file to the screen, the process is terminated before I can make use of it. If I wanted cat
, I'd use it.
如何以这种方式执行程序? / p>
How do I execute a program in this fashion?
推荐答案
您可以使用 proc_open
通过管道的过程。但是,它似乎不太允许通过管道的用户交互,因为它基本上降级到 cat
命令。这是我的第一个(失败的)方法:
You could use proc_open
to feed input to and get output back from a process via pipes. However, it doesn't seem like less allows for user interaction via pipes as it basically degrades to a cat
command. Here's my first (failed) approach:
<?php
$dspec = array(
0 = array('pipe', 'r'), // pipe to child process's stdin
1 = array('pipe', 'w'), // pipe from child process's stdout
2 = array('file', 'error_log', 'a'), // stderr dumped to file
);
// run the external command
$proc = proc_open('less name_of_file_here', $dspec, $pipes, null, null);
if (is_resource($proc)) {
while (($cmd = readline('')) != 'q') {
// if the external command expects input, it will get it from us here
fwrite($pipes[0], $cmd);
fflush($pipes[0]);
// we can get the response from the external command here
echo fread($pipes[1], 1024);
}
fclose($pipes[0]);
fclose($pipes[1]);
echo proc_close($proc);
我想对于某些命令,这种方法可能实际上工作 - 并且有一些示例在php联机帮助页 proc_open
这可能有助于查看 - 但对于更少
,你得到整个文件, ,可能是因为Viper_Sb的回答提到的原因。
I guess for some commands this approach might actually work - and there are some examples in the php manpage for proc_open
that might be helpful to look over - but for less
, you get the whole file back and no possibility for interaction, maybe for reasons mentioned by Viper_Sb's answer.
...但似乎很容易模拟少
一切你需要的。例如,您可以将命令的输出读取到一个行数组中,并将其以一定大小的块提供:
...But it seems easy enough to simulate less
if that's all you need. For example, you could read the output of the command into an array of lines and feed it in bite-sized chunks:
<?php
$pid = popen('cat name_of_file_here', 'r');
$buf = array();
while ($s = fgets($pid, 1024))
$buf[] = $s;
pclose($pid);
for ($i = 0; $i < count($buf)/25 && readline('more') != 'q'; $i++) {
for ($j = 0; $j < 25; $j++) {
echo array_shift($buf);
}
}
这篇关于执行“少”从命令行PHP w /滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!