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

新手上路,请多包涵

我正在尝试将 tshark(或与此相关的任何 shell 命令)写入文件。我试过使用 decodeencode 但它仍然对我大喊 split 方法不能使用数据类型。

在“捕获停止”行之后,我的尝试仍在代码中作为注释。 I have also tried r , a and a+ as the open modes but I actually get output with the 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")

原文由 axxic3 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 406
2 个回答

如果您的问题归结为:

我试过使用解码和编码,但它仍然对我大喊 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'

为了拆分 bytes ,还必须提供 bytes 对象。解决方法很简单:

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

原文由 metatoaster 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

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

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

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

 # WRONG!
blah.decode()

也可以看看:

decode 文档。

原文由 Timur Shtatland 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题