struct.error: unpack requires a buffer of 2 bytes - file problem - struct

script tells me that unpack requires a buffer of 2 bytes.
maybe someone finds that error.
Thats a script to read a file with hex adresses and compare it with clear text file.
But everytime i get this struct.error
Traceback (most recent call last):
File "/home/starshield/deye/test.py", line 290, in <module>
params.parse(raw_msg, start, end - start + 1)
File "/home/starshield/deye/test.py", line 30, in parse
self.parsers[j['rule']](rawdata, j, start, length)
File "/home/starshield/deye/test.py", line 96, in try_parse_unsigned
temp = struct.unpack('>H', rawData[offset:offset + 2])[0]
struct.error: unpack requires a buffer of 2 bytes
code line 27 to 34:
def parse(self, rawdata, start, length):
for i in self._lookups['parameters']:
for j in i['items']:
self.parsers[j['rule']](rawdata, j, start, length)
return
def get_result(self):
return self.result
code line 91 to 101
for r in definition['registers']:
index = r - start # get the decimal value of the register'
# print("Reg: %s, index: %s" % (r, index))
if (index >= 0) and (index < length):
offset = OFFSET_PARAMS + (index * 2)
temp = struct.unpack('>H', rawData[offset:offset + 2])[0]
value += (temp & 0xFFFF) << shift
shift += 16
else:
found = False
if found:
The last block is from 292 to 299
for i in range(start, end):
value = getRegister(raw_msg, i)
name = "Unknown"
for paramters in parameter_definition["parameters"]:
for item in paramters["items"]:
for reg in item["registers"]:
if reg == i:
name = item["name"]
not able to find the error

Related

TypeError: ord() expected string of length 1, but int found, Traceback (most recent call last):

I am getting an error while encrypting a file.
C:\Users\username>python xor_encryptor.py raw.txt > new.txt
Traceback (most recent call last):
File "C:\Users\username\xor_encryptor.py", line 19, in <module>
ciphertext = xor(plaintext, KEY)
File "C:\Users\username\xor_encryptor.py", line 10, in xor
output_str += chr(ord(current) ^ ord(current_key))
TypeError: ord() expected string of length 1, but int found
The xor_encryptor script is:
import sys
KEY = "x"
def xor(data, key):
key = str(key)
l = len(key)
output_str = ""
for i in range(len(data)):
current = data[i]
current_key = key[i % len(key)]
output_str += chr(ord(current) ^ ord(current_key))
return output_str
def printCiphertext(ciphertext):
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
try:
plaintext = open(sys.argv[1], "rb").read()
except:
print("File argument needed! %s " % sys.argv[0])
sys.exit()
ciphertext = xor(plaintext, KEY)
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
Kindly give an appropriate solution.

Concatenating strings not bytes

I'm trying to link my IP camera to my a AWS service and there's 2 ways I can do this, either with my built in computer camera (runs fine) and a IP camera. The code I'm using is from https://github.com/aws-samples/amazon-rekognition-video-analyzer which is writing in Python 2.7(but I'm doing it in python 3), I already converted the code to python 3 (using python 2to3).but when I run the code I keep getting this error of only concatenate strings not bytes:
I'm new to python so for what I have research is that 2to3 will do must of the work, but I'm pretty sure this part of converting bytes to strings is not in there and I'm not sure how to handle this conversion/parsing.
Traceback (most recent call last):
File "video_cap_ipcam.py", line 140, in <module>
main()
File "video_cap_ipcam.py", line 104, in main
bytes += stream.read(16384*2)
TypeError: can only concatenate str (not "bytes") to str
video_cap_ipcam.py file:
def main():
ip_cam_url = ''
capture_rate = default_capture_rate
argv_len = len(sys.argv)
if argv_len > 1:
ip_cam_url = sys.argv[1]
if argv_len > 2 and sys.argv[2].isdigit():
capture_rate = int(sys.argv[2])
else:
print("usage: video_cap_ipcam.py <ip-cam-url> [capture-rate]")
return
print(("Capturing from '{}' at a rate of 1 every {} frames...".format(ip_cam_url, capture_rate)))
stream = urllib.request.urlopen(ip_cam_url)
bytes = ''
pool = Pool(processes=3)
frame_count = 0
while True:
# Capture frame-by-frame
frame_jpg = ''
bytes += stream.read(16384*2)
b = bytes.rfind('\xff\xd9')
a = bytes.rfind('\xff\xd8', 0, b-1)
if a != -1 and b != -1:
#print 'Found JPEG markers. Start {}, End {}'.format(a,b)
frame_jpg_bytes = bytes[a:b+2]
bytes = bytes[b+2:]
if frame_count % capture_rate == 0:
img_cv2_mat = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
rotated_img = cv2.transpose(cv2.flip(img_cv2_mat, 0))
retval, new_frame_jpg_bytes = cv2.imencode(".jpg", rotated_img)
#Send to Kinesis
result = pool.apply_async(send_jpg, (bytearray(new_frame_jpg_bytes), frame_count, True, False, False,))
frame_count += 1
if __name__ == '__main__':
main()
When you initially set the variable bytes to '', the variable becomes a string, which in Python 3 is considered a sequence of characters rather than a sequence of bytes. (A character can be expressed using multiple bytes.)
If you want bytes to be a sequence of bytes, initialize it as b'' instead. Then you can concatenate further bytes to it.

how to move a character to a certain inputted index

I am trying to make my own text editor where it asks for a file and prints a > that can then be moved to the specified index of the line so that it can then delete a character. I don't know the best way to move it. So far I have
def print_file(data, cursor):
"""Prints the file contents (data), with the cursor in the right place."""
# Variable fm will store the formatted representation
# of the file with position information, etc.
fm = ""
pos = 0
# Break the "file" (represented by a string) up into lines.
lines = data.split("\n")
for x, line in enumerate(lines):
length = len(line)
if length != 0:
# Edge case for the end of the "file".
if data[-1] != "\n" and x == len(lines) - 1:
length -= 1
fm += str("{0:70} |{1:3d}:{2:3d}|\n".format(line, pos, pos + length))
# If the cursor points to char on this line add it.
if pos <= cursor <= pos + length:
fm += " " * (cursor - pos) + "^\n"
# Start at the next character.
pos += length + 1
print(fm, end="")
#end of function
def move_cursor(location):
"""Moves the cursor to the right location"""
#end of function
cursor = 0
is_open = False
is_modified = False
file = str(input(">open "))
#Open filename
file == "(filename)"
file = open(file, "r")
file_data = file.read()
print_file(file_data, cursor)
command = str(input("> "))
#Move position
if command == "move(int)":
move_cursor(location)
I think the best way would be to make a function and then call it inside the loop, but am unsure how to actually get it to move to the index....

Curangle() throwing this error - TypeError: float() argument must be a string or a number

Below is the original code:
#Update the solar file for reporting
logsolar = open('/tools/inputs/solarvalues.txt','w')
writeline=("[myvars]\n")
logsolar.write(writeline)
writeline=("solar_heading: " + str(round((float(getsolarheading())),1)) + "\n")
logsolar.write(writeline)
writeline=("solar_elevation: " + str(round((float(getsolarangle())),1))+ "\n")
logsolar.write(writeline)
writeline=("actual_elevation: " + str(round((float(getcurangle())),1))+ "\n")
logsolar.write(writeline)
writeline=("actual_heading: " + str(round((float(getcurheading())),1))+ "\n")
logsolar.write(writeline)
logsolar.close()
The following is the error message:
Traceback (most recent call last):
File "solarrobot7-core.py", line 373, in <module>
writeline=("actual_elevation: " + str(round((float(getcurangle())),1))+ "\n")
TypeError: float() argument must be a string or a number
i've been through like seven pages of Google for this, but still can't figure out how to code this line so that it doesn't throw this error. Sorry it took so long. The following is from where curangle() is first called.
#Read the IMU to get the angle of incline (forwards/backwards)
#This is what we use for the solar panels, so we have to switch
#from 0 degrees on the normal axis to 0 degrees on the horizon
def getcurangle():
# The escape character for # is \x23 in hex
serialport.write(b"\x23o0 \x23f")
response = serialport.readline()
words = response.split(b",")
if len(words) > 2:
try:
if ((float(words[1]) -90) * -1) < 89:
curangle = ((float(words[1]) -90) * -1)
else:
curangle = 0
except:
curangle = 999
return curangle + AngleOffset
The "b" in .split(b",") was added to the original code to supposedly make this code run under Python-3.x.
Ignoring the exception, if response does not have a "," character to be split, then words[1] will not be filled and can't be converted to a float.
First check to make sure response contains a comma from serialpoint elsewhere in your code.
You can also check this by adding print response and then print words[1] to make sure words[1] is returning a number and not a null value.
With the except, we can assume that the return value is always an int (either words[1] is an int and is returned, or words[1] is not an int and 999 gets returned from the except) so the error is coming from AngleOffset.
Double check the value of AngleOffset.

What does this Python error mean?

This was my test code (Python 3.2)
import random
def singleMatch():
a = random.randint(1, 5050)
b = random.randint(1, 5050-a)
c = 5050-a-b
h = [a, b, c]
print(h)
computer = [841, 842, 3367]
score = 0
for i, j in zip(computer, h):
if i > j:
score = score + 1
if score == 2:
return 1
else:
return 0
def match(n):
matchScore = 0
for i in range(n):
s = singleMatch()
matchScore = matchScore + s
return matchScore
x = match(10000)
print(x)
When I run the code, I sometimes get this error:
Traceback (most recent call last):
File "D:\Ercan\blotto.py", line 32, in <module>
x = match(10000)
File "D:\Ercan\blotto.py", line 28, in match
s = singleMatch()
File "D:\Ercan\blotto.py", line 5, in singleMatch
b = random.randint(1, 5050-a)
File "C:\Python32\lib\random.py", line 215, in randint
return self.randrange(a, b+1)
File "C:\Python32\lib\random.py", line 193, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (1,1, 0)
I couldn't figure out what it means, or what I did wrong.
You are telling your program to create a random number between 1 and 5050 and store it in a. Afterwards you want to get another random number between 1 and 5050-a, now if a is 5050, you would ask it to generate a random number between 1 and 0.
reference
Short answer: the error means that a is sometimes equal to 5050.
Long answer: randint() returns a random number lying in the supplied range. If the upper bound is less than the lower bound, then the function fails because there is no actual range to process.
Your first call stores a random number between 1 and 5050 (inclusive) into a. Your second call stores a random number between 1 and 5050 - a (inclusive) into b. If the first call returns 5050, then the second call will fail because the supplied range will be invalid.

Resources