python 3 subprocess error in bytes

Francisco picture Francisco · May 25, 2013 · Viewed 15.8k times · Source

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

I jump the following error:

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

but it prints the following:

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

and if I change these two lines:

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

I print only part of the output

that fails?


I've solved this way:

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

but I get error:

Traceback (most recent call last): File "C:\Documents and Settings\francisco\Escritorio\k.py", line 6, in print (o.decode("utf-8")) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa3 in position 103: invalid start byte

I just print it like this:

print (o.decode("latin"))

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

Answer

unutbu picture unutbu · May 25, 2013

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

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'