【问题标题】:Run an interactive shell command from PHP in CLI mode在 CLI 模式下从 PHP 运行交互式 shell 命令
【发布时间】:2016-06-14 12:37:39
【问题描述】:

我有一个 PHP CLI 脚本,并希望从该脚本执行交互式 bash 命令(例如 less huge-file.txt)并获得相同的视图(使用 less 例如导航控件),就好像我直接从终端。

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

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

【问题讨论】:

  • 这很好。祝你好运(尽管除非你在 cli 模式下运行 PHP,否则这是不可能的)......你有编程问题吗?这个网站是用来提问的,而不是一个倾倒你的待办事项/需求列表的地方。
  • @MarcB 我认为更通用的问题更好?我一直在努力寻找一个好的、简短的解决方案,所以我想我会很好地分享我的发现并要求更好的解决方案?
  • @thatotherguy 我有一个 CLI 脚本,不需要任何网络访问。我改写了问题以使其更清楚。
  • 好吧,那没关系

标签: php bash shell interactive


【解决方案1】:
proc_open( 'less huge-file.txt', array( STDIN, STDOUT, STDERR), $pipes);

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

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

【讨论】:

  • @hek2mgl 嗯,也许这取决于环境?对我来说,在 Mac OS 10.9.5 上使用 PHP 7 CLI 可以正常工作。
  • 我使用php5.6进行测试。晚上我试试php7。
【解决方案2】:

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

我怀疑您是否真的希望使用 less 编写脚本(这会变得丑陋,head / tail / 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');

【讨论】:

    猜你喜欢
    • 2015-02-19
    • 2012-07-03
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多