0

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

MrStan12
  • 55
  • 6
  • If you are simply running the command `python3 Execute.py json.txt` then this will not work, because the contents of `json.txt` are never given to stdin. Instead the file name is just put into `sys.argv` – Lecdi Jun 01 '22 at 12:07
  • Thank you for your answer. Your comment made me realize something and allowed me to find part of the answer. Here is the correct syntax to access the stdin on windows: cmd /c 'python Execute.py < json.txt' (https://stackoverflow.com/questions/2148746/the-operator-is-reserved-for-future-use) – MrStan12 Jun 01 '22 at 13:16

2 Answers2

1

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.py < json.txt
python3 Execute.py json.txt
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
0

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',''))
JosefZ
  • 28,460
  • 5
  • 44
  • 83