[英]Split a list : TypeError: a bytes-like object is required, not 'str'
[英]Cannot split, a bytes-like object is required, not 'str'
我正在尝试将 tshark(或与此相关的任何 shell 命令)写入文件。 我试过使用decode
和encode
,但它仍然对我大喊split
方法不能使用数据类型。
在“捕获停止”行之后,我的尝试仍在代码中作为注释。 我也尝试过r
、 a
和a+
作为open
模式,但实际上我使用此处使用的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")
正确使用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
文档。
如果您的问题归结为:
我已经尝试过使用解码和编码,但是它仍然对我大吼大叫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']
对于 python3,你应该使用这种模式(从 python2 移动之后)
for line in res2.content.splitlines():
line = line.decode()
你不会得到下面的错误
类型错误:需要一个类似字节的对象,而不是“str”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.