Is there a way to item assignment for bytes object? [duplicate] - python

This question already has answers here:
Item assignment to bytes object?
(2 answers)
Closed 1 year ago.
I am trying to assign bytes to a portion of pcap data(using slice operation) as below. I am getting "TypeError: 'bytes' object does not support item assignment" when try to assign data [a[8:24] = new5]. If not supported, is there any way?
code:
x = rdpcap("ref.pcap")
for packet in x:
a = (bs.hexlify(bytes(packet.load)))
TTF = a[8:24]
print ("T1",TTF)
new0 = (TTF.decode('utf-8'))
print ("T1-decode",new0)
print ("T1-dec",int(new0, base=16))
new4 = hex(int(time.time()))[2:]
print ("new4",new4)
new5 = bytes(new4, encoding='utf8')
print ("new5",new5)
print (a[8:24])
a[8:24] = new5
output:
T1 b'60ac7bd500000000'
T1-decode 60ac7bd500000000
T1-decimal 6966078878393565184
new4 60af6be2
new5 b'60af6be2'
b'60ac7bd500000000'
Traceback (most recent call last):
File "<stdin>", line 15, in <module>
TypeError: 'bytes' object does not support item assignment

A bytestring is immutable. You need to make a copy.
data = b'this is a test'
new_data = data[:5] + b'was' + data[7:]
# or, using join():
# new_data = b''.join((data[:5], b'was', data[7:]))
new_data
output:
b'this was a test'
Alternatively, you could use a bytearray:
data = bytearray(b'this is a test')
data[5:7] = b'was'
data
output:
bytearray(b'this was a test')

Related

How to retrieve a data field that has wrong type in database?

I'm writing a python script to extract data from a existing encoded database and make the data readable.
Now I want to retrieve data from the database but a data field has wrong type: it should be BLOB but actually TEXT.
UPD: I know use ord() can make it work but I wonder whether it's a good idea. I prefer a way to read them as BLOB.
import sqlite3
dbName = 'db'
def decode(data):
key = b'111111111111'
n = len(data)
ret = bytearray(n)
for i in range(0, n):
ret[i] = data[i]^key[i%len(key)]
return ret.decode('utf-8')
db = sqlite3.connect(dbName)
cur = db.cursor()
print(dbName + ' connected')
with open('friends', 'r') as f:
for friend in f:
ret = cur.execute('select frienduin from ' + friend)
for row in ret:
frienduin = decode(row[0])
Traceback (most recent call last):
File "sqlsol.py", line 23, in <module>
frienduin = decode(row[0])
File "sqlsol.py", line 10, in decode
ret[i] = data[i]^key[i%len(key)]
TypeError: unsupported operand type(s) for ^: 'str' and 'int'
Since data is of type str, perhaps trying
ret[i] = int(data[i]) ^ key[i%n]
might work.

Why this Typerror : '>' not supported between instances of 'float' and 'FirefoxWebElement'?

I'm trying to code a script using Python and Selenium, to compare the numbers between value _metal, value_crystal and value_deut with gauss_met_req, gauss_crys_req, and gauss_deut_req.
This error keeps popping up
Traceback (most recent call last):
File "/home/badjorans/Desktop/stob/selenss.py", line 138, in <module>
if value_crystal > gauss_crys_req and value_metal > gauss_met_req and value_deuterium > gauss_deut_req :
TypeError: '>' not supported between instances of 'float' and 'FirefoxWebElement'
I tried to convert the numbers to float but the error keeps appearing.
metal = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[1]/span")
crystal = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[2]/span")
deuterium = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[3]/span")
blackmatter = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[5]/a/span")
energy = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[4]/span")
value_metal = float(metal.text)
value_deuterium = float(deuterium.text)
value_crystal = float(crystal.text)
value_energy = int(energy.text)
gauss_met_req = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[3]/div[2]/div[1]/form/div/div[2]/div[2]/ul/li[1]/div[2]")
print (gauss_met_req.text)
value_gauss_met = float(gauss_met_req.text)
gauss_crys_req = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[3]/div[2]/div[1]/form/div/div[2]/div[2]/ul/li[2]/div[2]")
print (gauss_crys_req.text)
value_gauss_crys = float(gauss_crys_req.text)
gauss_deut_req = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[3]/div[2]/div[1]/form/div/div[2]/div[2]/ul/li[3]/div[2]")
print (gauss_deut_req.text)
value_gauss_deut = float(gauss_deut_req.text)
print(value_metal)
print (value_crystal)
print(value_deuterium)
if value_crystal > gauss_crys_req and value_metal > gauss_met_req and value_deuterium > gauss_deut_req :
print ("we have enough resources to build Gauss Canon")
else:
print ("NOT ENOUGH RESOURCES")
You didn't convert gauss_crys_req, gauss_met_req, and gauss_deut_req to floats like you did with value_crystal, value_metal, and value_deuterium. You seem to already know how to get the text from an element and convert it to a float, so just use the same method for all the variables you are comparing in your conditional.

TypeError: Can't convert 'bytes' object to str implicitly in python?

I was trying out Twitter API but it give me this error:
Traceback (most recent call last):
File "D:/MAGIC/python/twitterdemo.pu.py", line 23, in
text += status.text.encode('utf-8')
TypeError: Can't convert 'bytes' object to str implicitly
Here is my code:
import sys
import operator
import requests
import json
import twitter
from watson_developer_cloud import PersonalityInsightsV2 as PersonalityInsights
twitter_consumer_key = ''
twitter_consumer_secret = ''
twitter_access_token = ''
twitter_access_secret = ''
twitter_api = twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret, access_token_key=twitter_access_token, access_token_secret=twitter_access_secret)
handle = "#somethingsoemthing"
statuses = twitter_api.GetUserTimeline(screen_name=handle, count=200, include_rts=False)
text = ""
for status in statuses:
print (status.text)
if(status.lang == 'en'): #Enligh tweets
text += status.text.encode('utf-8')
What am I doing wrong?
Your text is initialized as a str, and you're trying to add a bytes object (which is what status.text.encode('utf-8') returns) to it. Initialize text as a bytes object and that error should go away:
text = b''
Alternatively, you could skip encoding the text altogether and it should work:
text += status.text

Python 3.5 BytesIO error

I am making a project all in python 2.7 but it started to give some errors to me on the final parts since the documentation is in python 3.5. So i am changing everything to python 3.5, but it is giving me a error because of bytesIO. Can you help me to understand why, and what should i do? The error is coming from def repr on string_dinamica.write('P3\n'). I left all the code in case that it´s needed. Thanks for the help. NOTE: Just to confirm this works on python 2.7 but not in 3.5
from io import BytesIO
from cor_rgb_42347 import CorRGB
class Imagem:
def __init__(self, numero_linhas, numero_colunas):
self.numero_linhas = numero_linhas
self.numero_colunas = numero_colunas
self.linhas = []
for n in range(numero_linhas):
linha = []
for m in range(numero_colunas):
linha.append(CorRGB(0.0, 0.0, 0.0))
self.linhas.append(linha)
def __repr__(self):
string_dinamica = BytesIO()
string_dinamica.write('P3\n')
string_dinamica.write("#mcg#leim#isel 2015/16\n")
string_dinamica.write(str(self.numero_colunas) + " " \
+ str(self.numero_linhas) + "\n")
string_dinamica.write("255\n")
for linha in range(self.numero_linhas):
for coluna in range(self.numero_colunas):
string_dinamica.write(str(self.linhas[linha][coluna])+ " ")
string_dinamica.write("\n")
resultado = string_dinamica.getvalue()
string_dinamica.close()
return resultado
def set_cor(self, linha, coluna, cor_rgb):
"""Permite especificar a cor RGB do pixel na linha "linha",
coluna "coluna".
"""
self.linhas[linha-1][coluna-1] = cor_rgb
def get_cor(self, linha, coluna):
"""Permite obter a cor RGB do pixel na linha "linha",
coluna "coluna".
"""
return self.linhas[linha-1][coluna-1]
def guardar_como_ppm(self, nome_ficheiro):
"""Permite guardar a imagem em formato PPM ASCII num ficheiro.
"""
ficheiro = open(nome_ficheiro, 'w')
ficheiro.write(str(self))
ficheiro.close()
if __name__ == "__main__":
imagem1 = Imagem(5,5)
print(imagem1)
Traceback (most recent call last):
File "C:\Users\Utilizador\Desktop\Projectos Finais\Projecto_42347\imagem_42347.py", line 60, in <module>
print(imagem1)
File "C:\Users\Utilizador\Desktop\Projectos Finais\Projecto_42347\imagem_42347.py", line 19, in __repr__
string_dinamica.write('P3\n')
TypeError: a bytes-like object is required, not 'str'
For Python 3, just change BytesIO to StringIO. Python 3 strings are Unicode strings instead of byte strings, and __repr__ should return a Unicode string in Python 3.
If you try to return a bytes object like some other answers suggest, you will get:
TypeError: __repr__ returned non-string (type bytes)
As I mentioned on my comment, BytesIO requires byte-like object.
Demo:
>>> from io import BytesIO
>>>
>>> b = BytesIO()
>>>
>>> b.write('TEST\n')
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
b.write('TEST\n')
TypeError: 'str' does not support the buffer interface
>>>
>>>
>>> b.write(b'TEST\n')
5
>>> v = b.getbuffer()
>>>
>>> v[2:4]=b'56'
>>>
>>> b.getvalue()
b'TE56\n'
So add to the beginning of your the param. in you pass to write method, b(for binary).

Why expected string become an tuple [duplicate]

This question already has answers here:
member variable string gets treated as Tuple in Python
(3 answers)
Closed 6 years ago.
I expected the variable output_format to be a string. But when I ran the script it gave me a tuple type and threw an exception.
If I run in Python interpreter, it gave me an expected string.
('--sout "#standard{access=file,vcodec=h264,dst=c0_s0_h264_640x480_30_vbr_500_99_40000000.mp4}"',)
'h264'
<type 'str'>
Traceback (most recent call last):
File "streaming_verification/src/streaming_verification/scripts/streaming_verification.py", line 184, in run
self.streaming.dump_file(export_fname, 5, codec_type)
File "streaming_verification/src/streaming_verification/scripts/streaming.py", line 57, in dump_file
cmd_str = " ".join(cmd)
TypeError: sequence item 3: expected string, tuple found
Script source code:
def dump_file(self,
fname='',
period=10,
codec_type="h264"):
if "h264" == codec_type:
output_format = "--sout \"#standard{access=file,vcodec=h264,dst=%s.mp4}\"" % fname,
elif "mjpeg" == codec_type:
output_format = "--sout \"#standard{access=file,vcodec=mjpg ,dst=%s.avi}\"" % fname,
elif "mpeg" == codec_type :
output_format = "--sout \"#standard{access=file,vcodec=h264,dst=%s.mp4}\"" % fname,
pp(output_format)
cmd =[
"vlc",
"-I dummy",
"--rtsp-tcp {0}".format(self.conn_cfg["rtsp_link"]),
output_format,
"--stop-time {0} vlc://quit ".format(period)
]
cmd_str = " ".join(cmd)
self.run(cmd_str)
Your output_format is always tuple, because you put a comma after each possible value:
output_format = "..." % fname,
# ---------------------------^
Remove those commas and your cmd_str will once again only contain strings.
Python tuples are formed by such commas; the parenthesis are only needed when not using them would lead to ambiguity:
>>> 1
1
>>> 1,
(1,)
>>> type(_)
<class 'tuple'>

Categories

Resources