axxic3
axxic3

Reputation: 361

Cannot split, a bytes-like object is required, not 'str'

I am trying to write a tshark (or any shell command for that matter) to a file. I've tried using decode and encode but it still yells at me that the split method cannot use the datatype.

My attempts are still in the code as comments, after the "capturing stopped" line. I have also tried r, a and a+ as the open modes but I actually get output with the ab+ mode used here so I opted to keep it. Even using a+ mode said "blah" was bytes. I would like to keep the file appended with the output.

import subprocess
import datetime

x="1"
x=input("Enter to continue. Input 0 to quit")
while x != "0":
    #print("x is not zero")
    blah = subprocess.check_output(["tshark -i mon0 -f \"subtype probe-req\" -T fields -e wlan.sa -e wlan_mgt.ssid -c 2"], shell=True)
    with open("results.txt", 'ab+') as f:
        f.write(blah)
    x=input("To get out enter 0")
print("Capturing Stopped")

# blah.decode()
#blah = str.encode(blah)

#split the blah variable by line
splitblah = blah.split("\n")

#repeat  for each line, -1 ignores first line since it contains headers
for value in splitblah[:-1]:

    #split each line by tab delimiter
    splitvalue = value.split("\t")

#Assign variables to split fields
MAC = str(splitvalue[1])
SSID = str(splitvalue[2])
time = str(datetime.datetime.now())

#write and format output to results file
with open("results.txt", "ab+") as f:
    f.write(MAC+" "+SSID+" "+time+"\r\n")

Upvotes: 23

Views: 42680

Answers (3)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use decode() correctly: either in two steps (if you want to reuse blah):

blah = blah.decode()
splitblah = blah.split("\n")
# other code that uses blah

or inline (if you need it for single use):

splitblah = blah.decode().split("\n")

Your issue with using decode() was that you did not use its return value. Note that decode() does not change the object (blah) to assign or pass it to something:

# WRONG!
blah.decode()

SEE ALSO:
decode docs.

Upvotes: 10

Ravi Singh
Ravi Singh

Reputation: 7

For python3, you should use this kind of pattern (after moving from python2)

for line in res2.content.splitlines():
   
    line = line.decode()

you will not get the below error

TypeError: a bytes-like object is required, not 'str'

Upvotes: -1

metatoaster
metatoaster

Reputation: 18908

If your question boils down to this:

I've tried using decode and encode but it still yells at me that the split method cannot use the datatype.

The error at hand can be demonstrated by the following code:

>>> blah = b'hello world'  # the "bytes" produced by check_output
>>> blah.split('\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

In order to split bytes, a bytes object must also be provided. The fix is simply:

>>> blah.split(b'\n')
[b'hello world']

Upvotes: 40

Related Questions