python 3子进程错误以字节为单位 [英] python 3 subprocess error in bytes

查看:86
本文介绍了python 3子进程错误以字节为单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Very good, I have a little problem with the output of the thread, I get in unicode or I think and not let me convert it to utf-8, this is the code:

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'**

如果我打印后仍保留打印并让我打印:

if I print leaving the print and if you let me:

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"))

我只打印输出的一部分

我已经解决了这种方式:

I've solved this way:

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

但我收到错误消息:

跟踪(最近一次通话最近):
文件 C:\Documents and Settings\francisco\Escritorio\k.py,第6行,
打印(o.decode( utf-8))
UnicodeDecodeError: utf-8编解码器无法解码位置103的字节0xa3:无效的起始字节

我只是这样打印:

print (o.decode("latin"))

在拉丁语中,我可以更正此错误并在utf-8中打印出来吗?

in latin, I can correct this error and print it in utf-8?

推荐答案

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

o, the first return value from proc.communicate(), is already bytes not str, so it is already encoded in some encoding (or you could think of it as just a sequence of bytes).

在Python3中,个字节可以解码 str str 可以编码 bytes ,但是 bytes 永远不能编码, str 永远不能解码。这就是Python3抱怨的原因

In Python3 bytes can be decoded to str, and str can be encoded to bytes, but bytes can never be encoded, and str can never be decoded. That is why Python3 is complaining,

AttributeError: 'bytes' object has no attribute 'encode'

这篇关于python 3子进程错误以字节为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆