I have
cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
for line in cmd.stdout:
columns = line.split(' ')
print (columns[3])
have error in line 3 Type Str doesnt support the buffer API.
What am i doing wrong i am on Python 3.3
A simpler solution of the first part of Martijn Pieters's answer is to pass the
universal_newlines=True
argument to thePopen
call.I would even simplify this to:
NOTE: If file or directory names contain spaces, use
os.listdir('.')
as suggested in Martijn Pieters's answer or something like the following:You are reading binary data, not
str
, so you need to decode the output first. If you set theuniversal_newlines
argument toTrue
, thenstdout
is automatically decoded using the result of thelocale.getpreferredencoding()
method (same as for opening text files):If you use Python 3.6 or newer, you can use an explicit
encoding
argument for to thePopen()
call to specify a different codec to use, like, for example, UTF-8:If you need to use a different codec in Python 3.5 or earlier, don't use
universal_newlines
, just decode text from bytes explicitly.You were trying to split a
bytes
value using astr
argument:By decoding you avoid that problem, and your
print()
call will not have to prepend the output withb'..'
either.However, you probably just want to use the
os
module instead to get filesystem information:Better use binascii.b2a_uu that converts binary data to a line of ASCII characters