【发布时间】:2021-12-24 21:10:46
【问题描述】:
我正在构建一个调用 Powershell 来获取数据的 API。
当我使用 subprocess.check_output
运行命令时,除了 '*' 一切正常powershell_call = json.loads(subprocess.check_output([
'powershell.exe',
f'{cmdlet_name} -Identity "{identity}" -Server {server} -Properties * | ConvertTo-Json -Depth {jsonDepth}'
]))
错误信息:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 8110: invalid start byte
我试着把调用方式改成这样:
powershell_call = subprocess.Popen(
[
"powershell.exe",
f'{cmdlet_name} -Identity "{identity}" -Server {server} -Properties * | ConvertTo-Json -Depth {jsonDepth}'
],
shell=True,
stdout = subprocess.PIPE,
encoding = 'utf-8',
universal_newlines = True
)
但它给出了相同的错误信息。
在通过子进程调用 PowerShell 时有什么方法可以传递星号?
--- 编辑 ---
原来我只需要将 subprocess.check_output 更改为 subprocess.getoutput
【问题讨论】:
-
看起来您的脚本需要来自 PowerShell 的 UTF-8 编码输出。为此,您必须将控制台的输出代码页设置为
65001。 (很可能是命令的 output 是问题所在,而不是*char. int 命令本身)。 -
太棒了,感谢您的回复!我查找了您所写内容的信息,发现我需要做的就是将 subprocess.check_output 更改为 subprocess.getoutput。再次感谢!
标签: python powershell