PHP CLI:如何在使用管道时从键盘STDIN读取?

时间:2014-08-09 17:43:56

标签: php scripting command-line-interface

我正在创建一个脚本,通过以下方式接受数据输入:

  1. filename(打开.txt文件进行阅读)
  2. pipe(通过" php:// stdin&#34读取)
  3. 在这两种情况下,我都需要从键盘,stdin获取控件;

    1。使用pipe(stdin)打开文件时,我可以从

    中读取键盘
    ./myscript.php --file filename.txt
    

    然后

    <?php
    
    $DATA = file_get_contents("filename.txt");
    // etc loop
    $input = fopen("php://stdin", "r"); // works
    stream_set_blocking($input, false);
    $key = fgetc($input); // get input from keyboard
    echo $key;
    
    ?>
    

    2。但是当使用管道时,这不起作用,例如:

    cat filename.txt | ./myscript.php
    

    然后

    <?php
    
    $DATA = file_get_contents("php://stdin");
    // etc loop
    $input = fopen("php://stdin", "r"); // does not works
    stream_set_blocking($input, false);
    $key = fgetc($input); // get input from keyboard
    echo $key;
    
    ?>
    

    为什么我不能在第二种情况下从键盘读取?感谢。

1 个答案:

答案 0 :(得分:0)

我能够直接从/dev/tty

进行阅读
<?php

$DATA = file_get_contents("php://stdin");
// etc loop
$input = fopen("/dev/tty", "r"); // this works, as stdin == pipe
stream_set_blocking($input, false);
$key = fgetc($input); // get input from keyboard
echo $key;

?>

我在这里找到了答案:

How to make Perl use different handles for pipe input and keyboard input?

此外:

Can I prompt for user input after reading piped input on STDIN in Perl?

相关问题