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

2
  • 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 Commented Jun 1, 2022 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' (stackoverflow.com/questions/2148746/…) Commented Jun 1, 2022 at 13:16

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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',''))

1 Comment

Thank you for your answer, it does not work for me I do not have access to the sys.stdin lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.