如何使用shell_exec((设置虚拟终端大小?我试过
function shell_exec_with_size(string $cmd, int $columns = 999, int $rows = 999): string
{
$cmd = '/bin/bash -c ' . escapeshellarg("stty columns {$columns}; stty rows {$rows};{$cmd}");
return shell_exec($cmd);
}
但这似乎没有任何效果,至少columns属性没有实际应用(不知道rows属性是否设置(。。
具有yum check-updates
根据列大小改变格式的问题;"小";列大小和一个长的更新名称,格式为
python-devel.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-libs.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-pillow.x86_64 2.0.0-23.gitd1c6db8.amzn2.0.1
amzn2-core
(其中python pillow的更新名称2.0.0-23.gitd1c6db8.amzn2.0.1
太长(,但由于终端尺寸较大,它被打印为
python.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-devel.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-libs.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-pillow.x86_64 2.0.0-23.gitd1c6db8.amzn2.0.1 amzn2-core
python2-rpm.x86_64 4.11.3-48.amzn2.0.2 amzn2-core
我正在尝试以编程方式解析列表,因此指定终端大小将有助于从yum check-updates
获得一致的格式。。。我还检查了百胜是否可能用制表符或其他东西分隔属性:它没有。它似乎只是用空格或换行符和空格来分隔属性,这取决于终端的大小。
。。。不知道为什么,但使用util-linux的script
命令而不是bash可以使stty发挥作用,结合script --command 'stty columns 999;cmd' /dev/null
工作:
function shell_exec_with_size(string $cmd, int $columns = 999, int $rows = 999): string
{
$cmd = "stty columns {$columns}; stty rows {$rows};{$cmd}";
$cmd = 'script --quiet --return --command ' . escapeshellarg($cmd) . ' /dev/null';
return shell_exec($cmd);
}
(我还怀疑,但尚未证实,script
在幕后呼叫/bin/sh
(
另一种方法是通过管道将其输出到文件中,然后用file_get_contents
读回
编辑:虽然现在我想起来了,但我不确定yum
将如何处理管道传输到文件。你能看看/var/log/yum
吗?
<?php
/*
Author: hanshenrik
Question: php how to specify virtual terminal size in shell_exec()?
URL: https://stackoverflow.com/questions/74179969/php-how-to-specify-virtual-terminal-size-in-shell-exec
Tags: php, terminal, pty
*/
function shell_exec_with_file_output(string $cmd, string $tmp_file = 'shell_exec_with_file_output'): string
{
shell_exec($cmd . ' > ' . $tmp_file);
$content = file_get_contents($tmp_file);
unlink($tmp_file);
return $content;
}
$output = shell_exec_with_file_output('bash ./test.sh');
var_dump($output);
然后使用test.sh
#!/bin/bash
echo "python.x86_64 2.7.18-1.amzn2.0.5 amzn2-core"
echo "python-devel.x86_64 2.7.18-1.amzn2.0.5 amzn2-core"
echo "python-libs.x86_64 2.7.18-1.amzn2.0.5 amzn2-core"
echo "python-pillow.x86_64 2.0.0-23.gitd1c6db8.amzn2.0.1 amzn2-core"
echo "python2-rpm.x86_64 4.11.3-48.amzn2.0.2 amzn2-core"
输出:
string(975) "python.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-devel.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-libs.x86_64 2.7.18-1.amzn2.0.5 amzn2-core
python-pillow.x86_64 2.0.0-23.gitd1c6db8.amzn2.0.1 amzn2-core
python2-rpm.x86_64 4.11.3-48.amzn2.0.2 amzn2-core
"