Home > OS >  Python cannot read Stdin input on Windows and reacts like an infinite loop
Python cannot read Stdin input on Windows and reacts like an infinite loop

Time:06-02

I have a problem that only appears on Windows 10 when I run a python script from the console (or a ProcessBuilder in Java) with an stdin input.

When I run this code on Ubuntu :

import sys
print(sys.stdin.read())

With this command :

python3 Execute.py < json.txt

I obtain on my console the content of json.txt : "Hello"

When I run this same command (without "<") with the same code on Windows the process reacts like an infinite loop. (What is problematic for my development environment)

My python version is 3.8.10 in both environments (ubuntu 20.04 WSL1 and Windows 10)

What am I doing wrong?

Thanks

CodePudding user response:

Here's my simple Windows command line parser. Takes parameters supplied in command line itself (sys.argv) as well as input redirected from a file (sys.stdin).

import sys
ii = 0
for arg in sys.argv:
    print ( "param #"   str( ii ), arg, "\t", type(arg))
    ii  = 1
if not sys.stdin.isatty():
    for arg in sys.stdin:
        print ( "pline   " , arg.replace('\n', '').replace('\r',''))

Output: python cliparser.py abc 222 "c d" < cliparser.py

param #0 cliparser.py    <class 'str'>
param #1 abc     <class 'str'>
param #2 222     <class 'str'>
param #3 c d     <class 'str'>
pline    import sys
pline    ii = 0
pline    for arg in sys.argv:
pline        print ( "param #"   str( ii ), arg, "\t", type(arg))
pline        ii  = 1
pline    if not sys.stdin.isatty():
pline        for arg in sys.stdin:
pline            print ( "pline   " , arg.replace('\n', '').replace('\r',''))

CodePudding user response:

In your case, you might want to explore the fileinput standard library, which works by reading the stdin (or a file, if supplied) line by line:

import fileinput
text = "".join(line for line in fileinput.input())
print(text)

Then you can invoke your script either ways:

python3 Execute < json.txt
python3 Execute json.txt
  • Related