【问题标题】:PHP CLI: How to read from keyboard STDIN when using pipe?PHP CLI:使用管道时如何从键盘 STDIN 读取?
【发布时间】:2014-08-10 07:24:49
【问题描述】:

我正在制作一个通过以下方式接受数据输入的脚本:

  1. 文件名(它会打开一个 .txt 文件以供阅读)
  2. 管道(通过“php://stdin”读取)

在这两种情况下,我都需要从键盘、stdin 获取控件;

1。 not 使用 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;

?>

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

【问题讨论】:

    标签: php scripting command-line-interface


    【解决方案1】:

    我可以直接从 /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?

    【讨论】: