2

I'm using Python3.8 to make a program that takes an input from the user with the help of sys.stdin. This is the code:

import sys

try:    
    file = open(sys.argv[1], "r")
    source = file.read()
    file.close()    
except:
    source = sys.stdin.read()
    
input("\nPress enter to continue... \n")

If the user doesn't provide an argument, the program continues with the standard input. The problem is: When I run the program, I get an error at the last line. Here is the output:

$ apt-get install google* --print-uris | ./scrFiles/pythonFiles/code.py

Press enter to continue... 
Traceback (most recent call last):
  File "./scrFiles/pythonFiles/code.py", line 12, in <module>
    input("\nPress enter to continue... \n")
EOFError: EOF when reading a line

What is wrong with my code? :/

FourPaws
  • 21
  • 1
  • 1
    Nothing is wrong with your code. It expects some input because you asked it to (`input("\n...)`). It never gets said input because the piped input doesn't have any more input. So it tells you it received an EOF signal where it expected a line of input – Pranav Hosangadi Dec 02 '20 at 22:31
  • @PranavHosangadi So how do I use input() command here without errors? Or am I not supposed to use input() and sys.stdin in the same code? I want that last last line to work – FourPaws Dec 02 '20 at 22:39
  • 1
    That is correct. When you pipe something into your program, the `stdin` is replaced by the contents of the pipe, so when you do `input(...)`, it expects something but receives nothing. Check this question out: [Pipe input to Python program and later get input from user](https://stackoverflow.com/questions/7141331/pipe-input-to-python-program-and-later-get-input-from-user) – Pranav Hosangadi Dec 02 '20 at 22:46
  • An alternative is to only ask for input if you aren't using a pipe, so move your `input(...)` inside the `try` block. – Pranav Hosangadi Dec 02 '20 at 22:49

0 Answers0