将Powershell脚本作为python子进程运行时的字符编码

时间:2019-06-27 08:34:05

标签: python powershell encoding character-encoding

当前,我正在编写一个小的Python应用程序的脚本,该应用程序执行PowerShell脚本。我的python脚本应该处理返回的字符串,但是不幸的是,我在编码特殊字符(如“ä”,“ö”,“Ü”等)时遇到了一些麻烦。如何返回Unicode / UTF-8字符串?

您可以在下面看到一个简单的示例。控制台输出为request.getAttribute()。我不明白为什么它不是b'\xc7\xcf\r\n',因为b'\xc3\xa4\r\n'应该是字符“ä”的正确UTF8编码。

try.py:

\xc3\xa4

script.ps1:

import subprocess
p = subprocess.check_output(["powershell.exe", ".\script.ps1"])
print(p)

我以某些方式采用了PowerShell脚本,但未获得预期的结果。

  1. 添加了return 'ä'

  2. 返回了"[Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8". Result: b'\xc3\x83\xc2\xa4\r\n'

谁可以帮助获取上层脚本的return [System.Text.Encoding]::UTF8.GetBytes("ä"). Result: b'195\r\n131\r\n194\r\n164\r\n'控制台输出?

1 个答案:

答案 0 :(得分:0)

我使用了“ pwsh”,因为我在Mac上运行了它,因此您可以在代码中使用“ powershell.exe” 试试这个:

import subprocess

p = subprocess.check_output(["pwsh", ".\sc.ps1"])
print(p.decode('utf-8'))

有关更多信息:您可以阅读here

Working Screenshot