簡體   English   中英

從帶滾動的命令行 PHP 執行“less”

[英]Execute "less" from command-line PHP w/ Scrolling

我想從 PHP 的命令行執行less和相似的程序。

我已經嘗試了通常的嫌疑人(exec、shell_exec、passthru 等),雖然其中許多人可以將文件轉儲到屏幕上,但在我可以使用它之前進程就終止了。 如果我想要cat ,我會使用它。

如何以這種方式執行程序?

您可以使用proc_open通過管道將輸入提供給流程並從流程中獲取輸出。 但是,它似乎並沒有允許通過管道進行用戶交互,因為它基本上降級為cat命令。 這是我的第一個(失敗的)方法:

<?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);

我想對於某些命令,這種方法可能確實有效——在proc_open的 php 聯機幫助頁中有一些示例可能有助於查看——但對於less ,你會返回整個文件並且不可能進行交互,可能是出於上述原因通過 Viper_Sb 的回答。

...但是如果這就是您所需要的,那么模擬less似乎很容易。 例如,您可以將命令的輸出讀取到一個行數組中,並將其分成一口大小的塊:

<?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);
  }
}

添加 exec('stty cbreak'); 到 PHP 腳本也解決了這個問題。

我將以下內容放在由 php.ini 中的 auto_prepend_file 設置定義的文件中

所以,我會做一些類似編輯 php.ini 的事情:

auto_prepend_file = /path/to/prepend.php

然后在 /path/to/prepend.php 中,我將添加以下行:

if (php_sapi_name() == 'cli') exec('stty cbreak');

我不確定原因。 我已經閱讀了 PHP 的錯誤報告。 我不確定版本。 我注意到以下設置存在問題:

$ php -v
PHP 5.3.3 (cli) (built: Jul 12 2013 20:35:47)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

但是,以下未顯示問題:

# php -v
PHP 5.3.26 (cli) (built: Oct 21 2013 16:50:03)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies
    with the ionCube PHP Loader v4.4.1, Copyright (c) 2002-2013, by ionCube Ltd.

值得注意的是,沒有問題的版本使用的是 cPanel,而另一個使用的是通過 yum 安裝的默認 CentOS 6。

我不相信這是可能的。 PHP 不是 VM/shell 環境,它訪問其他程序的命令都將控制權交還給它,通常在 PHP 運行時沒有交互。

最后一件事,嘗試使用反引號運算符,如果這不起作用那么我很確定你不能自己寫一些東西來睡眠並允許用戶輸入等......默認情況下沒有

`nano file.txt`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM