Python子进程引入空格

标签 python windows subprocess

我有一个 python 脚本,它使用 subprocess.Popen 来执行 Windows *.exe 文件。除一个 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)

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

最佳答案

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

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

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

Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Codec Base Classes.

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

标准编码表可以引用7.8.3. Standard Encodings .

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

关于Python子进程引入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34730502/

相关文章:

python - 使用 python 的 Google Pubsub 模拟器

python - 使用 scipy 的 solve_bvp 求解具有两个边界条件的一阶 BVP

angularjs - 带有 phantomjs 的 Protractor 永远挂起

python subprocess 命令中包含 json ('u' 前缀错误)

Python从HDFS读取文件作为流

python - authenticate() 未与自定义身份验证后端一起运行

python - 为 "Four fours"谜题制作解谜器

c++ - 将当前用户名写入Windows中的文件

c++ - Visual C++ 静态初始值设定项异常行为

python - 返回文件或目录未找到,但 bash 命令中未提及文件或目录?