Python 无法读取 Windows 上的 Stdin 输入,反应就像一个无限循环

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

当我从控制台(或 Java 中的 ProcessBuilder)使用标准输入 运行 一个 python 脚本时,我有一个问题只出现在 Windows 10输入。

当我 运行 这个代码在 Ubuntu :

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

使用此命令:

python3 Execute.py < json.txt

我在我的控制台上获得了 json.txt 的内容:“你好”

当我 运行 在 Windows 上使用相同代码的相同命令(不带“<”)时,该过程的反应就像一个无限循环。 (我的开发环境有什么问题)

我的 python 版本在两个环境中都是 3.8.10(ubuntu 20.04 WSL1 和 Windows 10)

我做错了什么?

谢谢

这是我的简单 Windows 命令行解析器。采用命令行本身提供的参数 (sys.argv) 以及输入 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',''))

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

在您的情况下,您可能想要探索 fileinput 标准库,它通过逐行读取标准输入(或文件,如果提供)来工作:

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

然后您可以通过以下任一方式调用您的脚本:

python3 Execute.py < json.txt
python3 Execute.py json.txt