簡體   English   中英

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 的內容:“Hello”

當我在 Windows 上使用相同的代碼運行相同的命令(沒有“<”)時,該過程的反應就像一個無限循環。 (我的開發環境有什么問題)

我的 python 版本在兩個環境中都是 3.8.10(ubuntu 20.04 WSL1 和 Windows 10)

我究竟做錯了什么?

謝謝

在您的情況下,您可能想要探索fileinput標准庫,它通過逐行讀取標准輸入(或文件,如果提供)來工作:

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

然后你可以通過任何一種方式調用你的腳本:

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

這是我的簡單 Windows 命令行解析器。 采用命令行本身( sys.argv )提供的參數以及從文件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 "cd" < cliparser.py

 param #0 cliparser.py <class 'str'> param #1 abc <class 'str'> param #2 222 <class 'str'> param #3 cd <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',''))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM