downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Consola interactiva> <Uso
Last updated: Fri, 20 May 2011

view this page in

Flujos de entrada/salida

CLI SAPI define algunas constantes para flujos de E/S que simplifican la programación en línea de comandos.

Constantes específicas de CLI
Constante Descripción
STDIN

Flujo abierto a stdin. Ahorra tener que abrirlo con

<?php
$stdin 
fopen('php://stdin''r');
?>
Si se desea leer una sola línea de stdin, puede usarse
<?php
$line 
trim(fgets(STDIN)); // lee una línea de STDIN
fscanf(STDIN"%d\n"$number); // lee un número de STDIN
?>

STDOUT

Flujo abierto a stdout. Ahorra tener que abrirlo con

<?php
$stdout 
fopen('php://stdout''w');
?>

STDERR

Flujo abierto a stderr. Ahora tener que abrirlo con

<?php
$stderr 
fopen('php://stderr''w');
?>

Teniendo esto en cuenta, no es necesario abrir por ejemplo un flujo a stderr, sino que puede usarse la constante en lugar del recurso de tipo flujo:

php -r 'fwrite(STDERR, "stderr\n");'
No es necesario cerrar explícitamente estos flujos, ya que se cierra automáticamente por PHP al finalizar el script.

Note:

Estas constantes no están disponibles si se leyera el script PHP a partir de stdin.



add a note add a note User Contributed Notes Flujos de E/S
Aurelien Marchand 04-Mar-2011 04:10
Please remember in multi-process applications (which are best suited under CLI), that I/O operations often will BLOCK signals from being processed.

For instance, if you have a parent waiting on fread(STDIN), it won't handle SIGCHLD, even if you defined a signal handler for it, until after the call to fread has returned.

Your solution in this case is to wait on stream_select() to find out whether reading will block. Waiting on stream_select(), critically, does NOT BLOCK signals from being processed.

Aurelien
James Zhu 09-Dec-2010 09:45
Example:

<?php
function ReadStdin($prompt, $valid_inputs, $default = '') {
    while(!isset(
$input) || (is_array($valid_inputs) && !in_array($input, $valid_inputs)) || ($valid_inputs == 'is_file' && !is_file($input))) {
        echo
$prompt;
       
$input = strtolower(trim(fgets(STDIN)));
        if(empty(
$input) && !empty($default)) {
           
$input = $default;
        }
    }
    return
$input;
}

// you can input <Enter> or 1, 2, 3
$choice = ReadStdin('Please choose your answer or press Enter to continue: ', array('', '1', '2', '3'));

// check input is valid file name, use /var/path for input nothing
$file = ReadStdin('Please input the file name(/var/path):', 'is_file', '/var/path');
?>

you can add more functions if you want.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites