无法拆分,需要类似字节的对象,而不是“str”

axx*_*ic3 8 python linux string shell decode

我正在尝试将 tshark(或任何与此相关的 shell 命令)写入文件。我试过使用 decode 和 encode 但它仍然对我大喊 split 方法不能使用数据类型。在“捕获停止”行之后,我的尝试仍在代码中作为注释。我也试过 r、a 和 a+ 作为开放模式,但我实际上使用这里使用的 ab+ 模式获得输出,所以我选择保留它。即使使用 a+ 模式也说“blah”是字节。我想将文件附加到输出中。谢谢!

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")
Run Code Online (Sandbox Code Playgroud)

met*_*ter 16

如果您的问题归结为:

我试过使用 decode 和 encode 但它仍然对我大喊 split 方法不能使用数据类型。

手头的错误可以通过以下代码演示:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

为了 split bytesbytes还必须提供一个对象。修复方法很简单:

>>> blah.split(b'\n')
[b'hello world']
Run Code Online (Sandbox Code Playgroud)


Tim*_*and 10

正确使用decode():分两步进行(如果你想重复使用blah):

blah = blah.decode()
splitblah = blah.split("\n")
# other code that uses blah
Run Code Online (Sandbox Code Playgroud)

或内联(如果您需要一次性使用):

splitblah = blah.decode().split("\n")
Run Code Online (Sandbox Code Playgroud)

您使用的问题decode()是您没有使用它的返回值。请注意,不会decode()更改对象 ( ) 以将其分配或传递给某些内容:blah

# WRONG!
blah.decode()
Run Code Online (Sandbox Code Playgroud)

另请参阅:
decode文档。