[英]Python - Readline Control-D after non-empty line does not work why?
I am new to python, and I am sorry if what I am asking seems odd.我是 python 的新手,如果我问的问题看起来很奇怪,我很抱歉。 I want to loop over each line on standard input and return a modified line to standard output immediately.
我想遍历标准输入的每一行并立即将修改后的行返回到标准 output。 I have code that works, mostly.
我的代码大部分都有效。 However I do not know how to make this work completely.
但是我不知道如何完全完成这项工作。
I have the following code我有以下代码
while True:
line = sys.stdin.readline()
if not line:
break
sys.stdout.write(line)
When being used interactively this will exit if there is an EOF on a new line, however if there is text before I type Control-D I must give the code twice before it will exit the line, and then once more before the loop will exit.当以交互方式使用时,如果在新行上有 EOF,这将退出,但是如果在我键入 Control-D 之前有文本,我必须在退出该行之前提供两次代码,然后在循环退出之前再提供一次.
How do I fix this.我该如何解决。
I think my answer from here can be copied immediately:我认为我在这里的回答可以立即复制:
It has to do with
^D
really does: it just stops the currentread(2)
call.它确实与
^D
有关:它只是停止当前的read(2)
调用。If the program does
int rdbytes = read(fd, buffer, sizeof buffer);
如果程序执行
int rdbytes = read(fd, buffer, sizeof buffer);
and you press^D
inbetween,read()
returns with the currently read bytes in the buffer, returning their number.然后在中间按
^D
,read()
返回缓冲区中当前读取的字节,并返回它们的编号。 The same happens on line termination;线路终端也是如此; the
\n
at the end is always delivered.最后的
\n
总是被传递。So only a
^D
at the start of a line or after another^D
has the desired effect of havingread()
return0
, signalizing EOF.因此,只有在一行开头或另一个
^D
^D
使read()
返回0
的预期效果,发出 EOF 信号。
And this behaviour, of course, affects Python code as well.当然,这种行为也会影响 Python 代码。
A strategy suggested in the python docs is: python 文档中建议的策略是:
for line in sys.stdin:
sys.stdout.write(line)
See the IO Tutorial .请参阅IO 教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.