Ziqian Pei
Ziqian Pei

Reputation: 11

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)

enter image description here

Can someone tell me the reason and how I can make input to test my program.

Thanks a lot.

Upvotes: 1

Views: 3554

Answers (1)

ivan_pozdeev
ivan_pozdeev

Reputation: 35998

sys.stdin.read() will read stdin until it hits EOF. Normally, this happens when that stream is closed by the other end (i.e. by whatever provides input).

This works if you run your program like 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.

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. 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).

So,

  • Use input() instead to input a single line, or
  • if you require multiple lines of input, use something that puts a limit on how much is read from 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).

Upvotes: 1

Related Questions