Sam
Sam

Reputation: 1232

Change python stdin stream to Windows Console input

I want to run a python 3 script giving it a file via stdin or manually typing data.

E.g. let's suppose I want to print the contents of an input with one line. The script, called app.py would look something like this:

from sys import stdin

print("Input says:"+stdin.readline())

Then, I could run it in both of the following ways:

1. Passing a file as stdin

python app.py < input.txt

2. Prompt the user for the input

python app.py

My problem is that in both cases, after reading stdin I would like to prompt the user for some extra data. Following the before mentioned example it would be:

from sys import stdin

print("Input says:"+stdin.readline())

print("Did you like that? (Yes/No)")
ans = input() # This line is the issue!
if( ans == "Yes"):
    print("You liked it!")    

The commented line above works perfectly for case 2, but for case 1 it throws an EOFError: EOF when reading a line error because it tries to read from the file.

I would like to know if before that line I could do something like

sys.stdin = SOMETHING

Where SOMETHING represents the Windows Console input. I think that if I could do that, then both cases would work properly.

Upvotes: 1

Views: 7216

Answers (1)

jfs
jfs

Reputation: 414855

You could consider both cases to be the same (ignore the difference). Your script just reads two lines from stdin. stdin may be redirected from a file or it can be attached to the console, your script can work the same in many cases:

print("Read the first line from stdin", input())
answer = input("Did you like that? (Yes/No): ") # read 2nd line
if answer == "Yes":
    print("You liked it!")

See executable code example.

Q: What I wanted was to read some inputs from a file OR from the console (depending on the parameters used when the app was ran). Some other lines I wanted them to be always read from the console.

To read from the console directly regardless whether stdin is redirected from a file or not, you could use msvcrt.getwch(). See example usage in getpass.win_getpass().

If you have issues with accepting Unicode input; install win_unicode_console package. You can enable it globally for your python installation or for a specific user or for a script as a whole or temporarily using win_unicode_console.enable()/.disable(). To force it to use console, you could set sys.stdin=None temporarily if stdin is redirected or call ReadConsoleW() yourself (cumbersome).

Upvotes: 1

Related Questions