我想列出在本地Windows计算机上运行的服务。为此,我正在使用此代码:
with Popen(["net", "start"], stdout=PIPE, stderr=PIPE) as p:
stdout, stderr = p.communicate() # type: (bytes, bytes)
输出的一部分看起来像这样(德语Windows版本:]:>
Folgende Windows-Dienste sind gestartet: Anmeldedienst [...] Benachrichtigungsdienst für Systemereignisse
将字节解码为字符串应该很容易。我检查了文档,并在命令行上找到了本地编码:
>>> import locale >>> locale.getpreferredencoding() 'cp1252'
因此,我想解码字节:
lines = stdout.decode('cp1252')
但是,对于示例中列出的变音符号
ü
,我收到一条错误消息:
File "test.py", line 511, in my_func
lines = stdout.decode('cp1252')
File "C:\Python344\lib\encodings\cp1252.py", line 15, in decode
return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 152: character maps to <undefined>
ü
我很茫然,为什么不能翻译。
注意:
U+00FC ü c3 bc LATIN SMALL LETTER U WITH DIAERESIS
用作universal_newslines=True
调用时,可以规避整个测试过程,但是使用它使我分析了编码问题所在。Popen
构造函数添加了Popen
选项,也许这可以避免这样的问题。可悲的是,Python 3.4是某些LTS Linux版本中包含的版本。编辑1:这里有些事。尽管Python 3.4文档指出Windows上的默认编码为cp1252,但是在CLI上运行命令并重定向到文件时,该文件在IBM850中进行了编码。最好的猜测是encoding=
不返回CLI的编码。
编辑2:使用locale.getpreferredencoding()
对标准输出进行解码的过程就像一个超级按钮。这意味着对ibm850
调用使用universal_newlines=True
确实会使用Popen
返回的编码,但是,这是解码CLI输出的错误编码。
我想列出在本地Windows计算机上运行的服务。为此,我使用以下代码:将Popen([“ net”,“ start”],stdout = PIPE,stderr = PIPE)作为p:stdout,stderr = p.communicate()#...
解决方案是: