python stdin: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte

python stdin: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte

我正在尝试使用 stdin(标准输入)作为我的代码的输入。

这就是我目前的实施方式。我想看看它是否提供了我想要的输出。

import sys

for i in sys.stdin.readlines():
    print(i.strip())

我打算在它给出的地方打印多行字符串

(venv) Test@Test-MacBookPro pythonProject1 % /Users/Test/PycharmProjects/pythonProject1/venv/bin/python /Users/Test/PycharmProjects/pythonProject1/proto_1.py < /Users/Test/PycharmProjects/pythonProject1/venv/bin/python /Users/Test/PycharmProjects/pythonProject1/input.txt    
Traceback (most recent call last):
  File "/Users/Test/PycharmProjects/pythonProject1/proto_1.py", line 3, in <module>
    for i in sys.stdin.readlines():
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte

这是我使用的输入文件:

apple
banana
carrot
ddddd
eeeee
fffff

有人知道为什么会这样吗?

是的,我知道。让我们看看您的命令行:

(venv) Test@Test-MacBookPro pythonProject1 % /Users/Test/PycharmProjects/pythonProject1/venv/bin/python /Users/Test/PycharmProjects/pythonProject1/proto_1.py < /Users/Test/PycharmProjects/pythonProject1/venv/bin/python /Users/Test/PycharmProjects/pythonProject1/input.txt    

删除路径只是为了更清楚:

python proto_1.py < python input.txt

您正在将 Python 解释器可执行文件作为输入文件传递。你为什么这么做?只需传递文件名:

/Users/Test/PycharmProjects/pythonProject1/venv/bin/python /Users/Test/PycharmProjects/pythonProject1/proto_1.py < /Users/Test/PycharmProjects/pythonProject1/input.txt