在 CLI 模式下从 PHP 运行交互式 shell 命令


Run an interactive shell command from PHP in CLI mode

>我有一个PHP CLI脚本,想要执行一个交互式bash命令(例如 less huge-file.txt ) 并从该脚本中获得相同的视图(带有less例如导航控件),就好像我直接从终端启动它一样。

正常的system()调用是不够的,因为它们不会暂停,只是一次返回所有输出(例如 less )。

感觉是我有一个 CLI 脚本来组织多个任务。其中一些使用复杂的 bash 命令,我只想从 PHP 调用 bash 脚本,但获得原始的终端行为。

proc_open( 'less huge-file.txt', array( STDIN, STDOUT, STDERR), $pipes);

这将调用命令并通过所有控件等传递,因此与正常less huge-file.txt没有区别。

仍然有点笨拙,但与我能找到的其他示例相比要短得多。

是的,这是可能的。我最近发布了一个项目,允许PHP获取并与真正的Bash shell进行交互。在这里获取:https://github.com/merlinthemagic/MTS

我怀疑你真的希望使用更少的脚本(这会变得丑陋,头/尾/sed/awk是你在文本操作中的朋友),但获得真正的shell行为是很有可能的。

下载后,您只需使用以下代码:

$shell    = 'MTS'Factories::getDevices()->getLocalHost()->getShell('bash', false);
//open file in less. $return1 will contain the view and the first part of the file you opened. The second argument is needed to delimit the return since less will not end in a shell prompt.
$return1  = $shell->exeCmd('less /path/to/huge-file.txt', 'huge-file.txt');
//quit less, you must do this or the shell will hang on the less prompt and will have to be forcefully terminated.
$return2  = $shell->exeCmd('q');