gpt4 book ai didi

python - 如何通过 PowerShell 读取 python 中的文本文件? window 10

转载 作者:太空宇宙 更新时间:2023-11-04 05:34:49 24 4
gpt4 key购买 nike

我在将文本文件读入我的 python 程序时遇到问题。

import sys

words = sys.stdin.readlines()

我正在通过标准输入读取文件,但是当我尝试执行该程序时出现此错误。

PS> python evil_61.py < evilwords.txt

At line:1 char:19
+ python evil_61.py < evilwords.txt
+ ~

The '<' operator is reserved for future use.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : RedirectionNotSupported

谁能告诉我如何运行这些类型的程序,因为它对我的类(class)很重要,而且我宁愿使用 Windows 而不是 Linux。

最佳答案

<对于 PowerShell 不支持的输入重定向,请使用 Get-Content改为在管道中:

Get-Content evilwords.txt | python evil_61.py 

注意:添加 -Raw switch - 将文件作为单个多行字符串读取 - 原则上会加快速度(以增加内存消耗为代价),但 PowerShell 总是附加一个换行符 到通过管道传输到外部程序的数据,从 PowerShell 7.2 开始(参见 this answer),因此目标程序通常会在末尾看到一个额外的空行Get-Content的逐行流式传输的默认行为避免了这种情况。

注意字符编码问题:

  • Get-Content , 在没有 -Encoding 的情况下参数,采用以下编码:

    • Windows PowerShell(最新和最终版本为 5.1 的内置 Windows 版本):事件的 ANSI 代码页,由事件的遗留系统暗示语言环境(非 Unicode 程序的语言)。
    • PowerShell (Core) 7+ :(无 BOM)UTF-8
  • 在通过管道传递线时,它们根据存储在 $OutputEncoding preference variable 中的编码进行(重新)编码,默认为:

    • Windows PowerShell:ASCII(!)
    • PowerShell(核心)7+:(无 BOM)UTF-8

如您所见,只有 PowerShell (Core) 7+ 表现出一致的行为,但不幸的是,从 PowerShell Core 7.2.0-preview.9 开始,这尚未扩展到从 外部程序捕获输出,因为控制接收数据解释的编码存储在 [Console]::OutputEncoding] 中, 仍然默认为系统的事件 OEM 代码页 - 参见 GitHub issue #7233 .

关于python - 如何通过 PowerShell 读取 python 中的文本文件? window 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35962197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com