PHP Funktion um colorierte Ausgabe von Shellprogrammen zu erhalten
PHP function fetch colored shell program output
Not much to say about it. It uses the script
command to emulate an existing TTY and
passes through the output of the executed shell command. You can also use the script
directly as shell command.
Hier gibt es nicht viel anzumerken. Die Funktion nutzt den script
-Befehl um eine TTY
zu emulieren und reicht die Ausgabe mit Escape-Zeichen an den Ausgabepuffer weiter. Das
untenstehende Skript kann auch direkt unter der Kommandozeile ausgeführt werden.
Function source code
Funktion
#!/usr/bin/php
<?
/**
* Executes a shell command given as first $argv[0] with arguments, prints
* the shell output including escape characters for colors etc, and returns
* the exit code of the program.
*
* To get the output text use ob_start() and ob_get_clean() before/after invoking
* this function.
*
* THE FUNCION REQUIRES THE SHELL PROGRAM "script" TO SIMULATE THE INTERACTIVE
* CONSOLE.
*
* @param array $argv
* @return int
*/
function shell_command_fetch_colored($argv=array()) {
if(empty($argv)) return false;
@ob_start();
$args = array(escapeshellcmd(array_shift($argv)));
while(!empty($argv)) {
$args[] = escapeshellarg(array_shift($argv));
}
$args = implode(' ', $args);
set_time_limit(5);
$exit_code = system("script -q -- /dev/null $args");
$text = explode("\n", ob_get_clean());
array_walk(&$text, function(&$line){$line=rtrim($line, "\r ");});
$text = trim(implode("\n", $text), "\n");
print $text;
return $exit_code;
}
/**
* Direct shell program usage (either "php sh2html.php <program> <arg1> <arg2>"
* or ./sh2html.php <program> <arg1> <arg2>" if this file is set executable.
*/
if(php_sapi_name() == 'cli' || basename($_SERVER['PHP_SELF']) === basename(__FILE__)) {
array_shift($_SERVER['argv']);
exit(shell_command_fetch_colored($_SERVER['argv']));
}