【问题标题】:Python subprocess introduces spacesPython子进程引入空格
【发布时间】:2016-04-16 06:59:28
【问题描述】:

我有一个 python 脚本,它使用 subprocess.Popen 来执行 Windows *.exe 文件。除一个以外的所有 EXE 都会产生预期的输出。当使用 print() 打印时,有问题的输出包括输出的每个字符之间的空格。

这是在 Windows 命令行中执行 EXE 时的输出:

C:\Python27>autorunsc.exe /accepteula

Sysinternals Autoruns v13.51 - Autostart program viewer
Copyright (C) 2002-2015 Mark Russinovich
Sysinternals - www.sysinternals.com


HKLM\System\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\StartupPrograms
   rdpclip
     rdpclip
     RDP Clip Monitor
     Microsoft Corporation
     6.1.7601.17514
     c:\windows\system32\rdpclip.exe
     20/11/2010 11:22

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit
   C:\Windows\system32\userinit.exe

这是用 Python 打印时的样子:

Sysinternals Autoruns v13.51 - Autostart program viewer
Copyright (C) 2002-2015 Mark Russinovich
Sysinternals - www.sysinternals.com


 H K L M \ S y s t e m \ C u r r e n t C o n t r o l S e t \ C o n t r o l \
 r m i n a l   S e r v e r \ W d s \ r d p w d \ S t a r t u p P r o g r a m
       r d p c l i p
           r d p c l i p
           R D P   C l i p   M o n i t o r
           M i c r o s o f t   C o r p o r a t i o n
           6 . 1 . 7 6 0 1 . 1 7 5 1 4
           c : \ w i n d o w s \ s y s t e m 3 2 \ r d p c l i p . e x e
           2 0 / 1 1 / 2 0 1 0   1 1 : 2 2

 H K L M \ S O F T W A R E \ M i c r o s o f t \ W i n d o w s   N T \ C u r
 n t V e r s i o n \ W i n l o g o n \ U s e r i n i t

我们可以清楚地看到空格,有趣的是前几行不包含空格。

这是代码:

p = subprocess.Popen('autorunsc.exe /accepteula', stderr=subprocess.STDOUT,
stdout=subprocess.PIPE, shell=True)
a=p.stdout.read()
print(a)

空格从何而来,如何删除?

【问题讨论】:

  • 最可能显而易见的答案是,这是 Microsoft 工具在内部使用 UTF-16 而不是 UTF-8 的结果。
  • 它们真的是 0x20 ASCII 空间,而不是 NUL 吗?我会冒险后者。
  • 当你忽略stderr时会发生什么(不要将它路由到STDOUT
  • 顺便说一句,这是一个非常特定于 Windows 的问题,所以我建议适当调整标题和标记。
  • @MartinKonecny,我会惊讶如果有文字空间去stderr与内容字符交错输出stdout。没有理由出现这种情况,而有充分的理由在输出中存在与 ASCII 字符交错的文字 NUL(因为 UTF-16 是 Microsoft 用于其注册表字符串和其他问题内容的本机格式) .

标签: python windows subprocess


【解决方案1】:

Windows 工具输出格式以 UTF-16 编码。

您必须使用str.decode 方法对输出进行解码以正确编码。引用文档:

str.decode([encoding[, errors]])

使用为编码注册的编解码器对字符串进行解码。编码 默认为默认字符串编码。可能会给出错误来设置一个 不同的错误处理方案。默认值为“严格”,这意味着 编码错误引发 UnicodeError。其他可能的值是 'ignore'、'replace' 和任何其他通过以下方式注册的名称 codecs.register_error(),参见 Codec Base Classes 部分。

a=p.stdout.read().decode('UTF16')

标准编码表可以参考7.8.3. Standard Encodings

由于您的输出似乎具有混合编码 [因为“空格”(实际上是 0x00 字符,而不是 0x20)仅存在于部分输出中],您可能需要在执行解码之前对字符串进行预处理或分区.

【讨论】:

  • 这行得通!输出中有 \0x00 字符。 .decode('UTF16') 成功了。我不需要输出的第一块,它总是固定长度,所以我只打印我需要的切片。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-08-11
  • 2020-11-25
  • 1970-01-01
  • 2017-08-18
  • 2017-11-19
  • 2019-05-19
  • 2022-08-03
  • 2021-01-04
相关资源
最近更新 更多