简体   繁体   English

使用sys.stdin.read()时,为什么不能从键盘输入?

[英]When using sys.stdin.read(), why I am not able to input from keyboard?

My code is as follows: 我的代码如下:

def function(a, b):
    while a != 0 and b != 0:
      ...

    return x

if __name__ == "__main__":
    input = sys.stdin.read()
    a, b = map(int, input.split())
    print(function(a, b))

When I try to run it, the program doesn't give me a chance to input. 当我尝试运行它时,该程序没有给我输入的机会。

I get the following traceback message: 我收到以下回溯消息:

ValueError: not enough values to unpack (expected 2, got 0)

在此处输入图片说明

Can someone tell me the reason and how I can make input to test my program. 有人可以告诉我原因以及如何输入测试程序的信息。

Thanks a lot. 非常感谢。

sys.stdin.read() will read stdin until it hits EOF. sys.stdin.read()将读取stdin直到达到EOF。 Normally, this happens when that stream is closed by the other end (ie by whatever provides input). 通常,当该流被另一端(即通过提供输入的任何内容)关闭时,会发生这种情况。

This works if you run your program like cat inputfile.txt | your_program 如果您像cat inputfile.txt | your_program这样运行程序,这将起作用cat inputfile.txt | your_program cat inputfile.txt | your_program . cat inputfile.txt | your_program But it will just keep reading endlessly in interactive mode when stdin is connected to your terminal, so the only way to close it from the other end is to close the terminal. 但是当stdin连接到您的终端时,它将仅以交互模式不断读取,因此从另一端关闭它的唯一方法是关闭终端。

Strictly speaking, you can make read() stop by inputting a EOF character on a line by itself which is Ctrl-D in Unix and Ctrl-Z in Windows -- and this works in a regular Python console. 严格来说,您可以通过在一行上单独输入一个EOF字符(在Unix中为Ctrl-D ,在Windows中为Ctrl-Z read()停止read() ,这在常规的Python控制台中有效。 But in IPython, this technique doesn't work: here in Windows, I see Ctrl-D as \\x04 and Ctrl-Z as a blank line and neither stops the read (whether this is a bug or by design is another question). 但是在IPython中,此技术不起作用:在Windows中,我将Ctrl-D\\x04 ,将Ctrl-Z视为空白行,并且都不会停止读取(这是错误还是设计上的另一个问题)。

So, 所以,

  • Use input() instead to input a single line, or 使用input()代替输入一行,或者
  • if you require multiple lines of input, use something that puts a limit on how much is read from stdin : 如果您需要多行输入,请使用限制从stdin读取多少的内容:

     ll=[] while True: l = input() # or sys.stdin.readline().rstrip() if not l: break ll.append(l) 

    This way, you're able to stop the program from asking for more input by entering a blank line. 这样,您可以通过输入空白行来阻止程序要求更多输入。

  • finally, there's sys.stdin.isatty() which allows you do invoke different code depending on whether the input is interactive (but for your task, this is probably an overkill). 最后,有sys.stdin.isatty() ,您可以根据输入是否为交互式来调用不同的代码(但是对于您的任务,这可能是一个过大的选择)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM