如何通过 PowerShell 在 python 中读取文本文件?Windows 10

Ola*_*dge 5 python powershell

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

import sys

words = sys.stdin.readlines()
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何运行这些类型的程序,因为它对我的课程至关重要,而且我宁愿使用 Windows 而不是 Linux。

mkl*_*nt0 7

由于<PowerShell 不支持输入重定向,Get-Content因此请在管道​​中使用:

Get-Content evilwords.txt | python evil_61.py 
Run Code Online (Sandbox Code Playgroud)

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

注意字符编码问题:

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

    • Windows PowerShell (Windows 内置版本,最新最终版本为 5.1):活动ANSI代码页,由活动旧系统区域设置(非 Unicode 程序的语言)暗示。
    • PowerShell(核心)7+:(无 BOM) UTF-8
  • 当这些行通过管道时,它们会根据存储在$OutputEncoding首选项变量中的编码进行(重新)编码,默认为:

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

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