python 3 子进程错误(以字节为单位)

问题描述 投票:0回答:1

非常好,我的线程输出有点问题,我输入unicode或者我认为不让我将其转换为utf-8,这是代码:

import subprocess,sys,time

string = b'dir'
process = subprocess.Popen('cmd.exe', shell=True,cwd="C:\\",stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write(string)
o,e=process.communicate()
process.wait()
process.stdin.close()
print (o.encode('utf-8'))

我跳转以下错误:

**Traceback (most recent call last):
  File "C:\Documents and Settings\francisco\Escritorio\k.py", line 12, in <module>
    print (o.encode(utf-8))
AttributeError: 'bytes' object has no attribute 'encode'**

如果我打印留下打印并且如果你让我:

print(o)

但它打印以下内容:

**b'Microsoft Windows XP [Versi\xa2n 5.1.2600]\r\n(C) Copyright 1985-2001 Microsoft Corp.\r\n\r\nC:\\>\xa8M\xa0s? '**

如果我改变这两行:

string = bytes('dir',encoding="utf-8") 
print (n[0].decode("latin"))

我只打印部分输出

失败了?


我已经这样解决了:

process.stdin.write("dir\n".encode())
o,e=process.communicate()
print (o.decode("utf-8"))

但我收到错误:

回溯(最近一次调用最后一次): 文件“C:\Documents and Settings rancisco\Escritorio\k.py”,第 6 行,位于 打印(o.decode(“utf-8”)) UnicodeDecodeError:“utf-8”编解码器无法解码位置 103 中的字节 0xa3:无效的起始字节

我只是这样打印:

print (o.decode("latin"))

在拉丁语中,我可以纠正这个错误并以 utf-8 打印它吗?

python python-3.x subprocess stdin encode
1个回答
12
投票

o
,来自
proc.communicate()
的第一个返回值,已经是
bytes
而不是
str
,因此它已经以某种编码进行了编码(或者您可以将其视为只是一个字节序列)。

在Python3中,

bytes
可以解码
str
str
可以编码
bytes
,但是
bytes
永远不能被编码,
str
永远不能被解码。这就是Python3抱怨的原因,

AttributeError: 'bytes' object has no attribute 'encode'
© www.soinside.com 2019 - 2024. All rights reserved.