如何在PHP控制台应用程序中刷新STDIN? [英] How do I flush STDIN in a PHP console application?

查看:54
本文介绍了如何在PHP控制台应用程序中刷新STDIN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用PHP构建的简单命令行实用程序,它运行良好.不幸的是,我们现在比精明的用户在处理数据时轻敲键盘要少得多.

I have a simple command line utility built with PHP and it works great. Unfortunately, we now have some lesser than savvy users pounding away at the keyboard while it's processing data.

是否有一种刷新STDIN的方法,以便它仅在我使用fgetc时才开始缓冲数据?

Is there a way to flush STDIN so it only starts buffering data from when I used fgetc?

我试图打开自己的STDIN管道,甚至通过遍历其中的内容来冲洗缓冲区,但这些方法不能处理多个CR.

I've tried opening my own STDIN pipe and even flushing the buffer by looping through what's in there which kind of works but doesn't handle multiple CRs.

倒带和fseek似乎对PHP中的STDIN没有任何作用.

Rewind and fseek don't seem to do anything with STDIN in PHP.

似乎这将是一个普遍的问题,但是没有很多.

Seems like it would be a common issue but not much out there.

PHP版本5.3.3

PHP version 5.3.3

(如果不需要,我不想使用ncurses)

(I don't want to use ncurses if I don't have to)

任何fgets或fgetc都会出现我的问题.例如,如果您有一个提示,指出某事正在处理中",然后开始键入内容,则输入将存储在STDIN中,因此当您稍后实际提示用户输入他们键入的内容时,会将其添加到缓冲区中.因此,如果他们在处理"时键入"abc",然后提示您输入的内容是"abc",再加上在进入fgets或fgetc时在提示符下键入的任何内容.因此,如果有人一直按ENTER键,而您正在使用fgets(或fgetc换一个"\ n"),则会得到代码过早的延续.

Any fgets or fgetc will exhibit my problem. For example, if you have a prompt indicating something is "processing" and then start typing away the input is buffered in STDIN so when you actually prompt the user later for something what they type is added to the buffer. So if they typed "abc" while "processing" and then you prompt for something their input is "abc" plus whatever they typed at the prompt by the time you get to fgets or fgetc. So if someone keeps hitting ENTER and you're using fgets (or fgetc wiating for a "\n") then you get premature code continuation.

例如:

echo "Processing";
sleep(10); // HIT ENTER A FEW TIMES HERE
echo "Input Something: ";
// REALLY NEED TO FLUSH STDIN HERE SOMEHOW
fgets(STDIN);

推荐答案

似乎PHP"readline"是处理此问题的好方法,我将继续使用它.

Seems that PHP "readline" is a good way to handle this and I'm going with it.

谢谢,全部!

这篇关于如何在PHP控制台应用程序中刷新STDIN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆