Search code examples
pythonstringshelldecode

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

Solution

  • 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']