string index out of range? - python - python

im buliding a chat and i'm keep getting the next error:
Traceback (most recent call last):
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 651, in <module>
main()
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 630, in main
print_message(data_from_server, len(temp_message), username)
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 265, in print_message
temp_l = data[0]
IndexError: string index out of range
i am trying to get the first char of the data string and convert it into int but i get this error
the problem is in the first line of the code
def print_message(d_temp, line_length, this_username):
temp_l = d_temp[0] #the problematic line
len_username = int(temp_l)
username_sender = d_temp[1:(len_username + 1)]
message_sent = d_temp[(len_username + 1): -4]
hour_time = d_temp[-4: -2]
min_time = d_temp[-2:]
printed_message = "\r" + hour_time + ":" + min_time + " " + username_sender + " : " + message_sent
print printed_message, # Prints this message on top of what perhaps this client started writing.
# if this client started typing message
complete_line_with_space(len(printed_message), line_length)
data- the data (string) from the server
line_length - the length of the temp massage
this_username - the client's username
thank you to all the helpers

empty d_temp will give this error.
This might be the reason:
>>> d_temp = ""
>>> d_temp[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

This happens because print_message is executed with an empty string as first parameter
print_message("",...)
This means the problem is somewhere else in your code.

Related

Syntax error with exec call to an object in Python 3

I really don't understand what causes the problem, could someone point it out for me please?
with shelve.open(obj_path) as obj:
for as_num in obj['as_number_list']: # ignore warning, obj['as_number_list'] is a list
temp = charge_as(obj['as_' + str(as_num)]) # temp is an object
as_test = temp # doing like this is ok
print(type(as_test))
exec("as_{}_obj = {}".format(as_num, temp)) # **error here**
And it gives syntax error like this:
<class 'instruments.AS'>
Traceback (most recent call last):
File "...", line 45, in <module>
exec("as_{}_obj = {}".format(as_num, temp))
File "<string>", line 1
as_1_obj = <instruments.AS object at 0x000002A86732E290>
^
SyntaxError: invalid syntax
I tried
exec("as_{}_obj = {}".format(as_num, temp.__dict__))
no error is shown but now as_{}_obj is of class 'dict' instead of class 'instruments.AS'
line 45:
exec("as_{}_obj = temp".format(as_num))

Snap7 get_real command not working, how to fix?

client = snap.client.Client()
client.connect('XXX.XXX.X.XXX', 0, 2) #IP address, rack, slot
db = client.db_get(20)
print(db)
intDB = []
for i in range(1, 122):
reading = client.db_read(20, i, 1)
realReading = snap.util.get_real(reading, 0)
array = [realReading]
intDB.append(array)
print(intDB)
This code is supposed to print a DB in bytearrays and then print an array with the floats values of the PLC output. However, when I run the code, I get the following error message:
Traceback (most recent call last):
File "C:/Users/Asus/PycharmProjects/PLC-Connection/main.py", line 19, in <module>
realReading = snap.util.get_real(reading, 0)
File "C:\Users\Asus\PycharmProjects\PLC-Connection\venv\lib\site-packages\snap7\util.py", line 357, in get_real
real = struct.unpack('>f', struct.pack('4B', *x))[0]
struct.error: pack expected 4 items for packing (got 1)
I think that the problem is reading the data:
reading = client.db_read(20, i, 1)
20 is the datablock, i is the index, and you read only 1 byte (3rd parameter).
For retrieving a real, you need 4 bytes read out.

Getting "TypeError: cannot use a string pattern on a bytes-like object" In my function. I am trying to print the MAC address to the screen

My get_current_mac function:
def get_current_mac(interface):
ifconfig_result = subprocess.check_output(["ifconfig", interface])
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
if mac_address_search_result:
return mac_address_search_result.group(0)
else:
print("[-] Could not read MAC address.")
I am then wanting to print the result to the screen:
options = get_arguments()
current_mac = get_current_mac(options.interface)
print("Current MAC address is: " + str(current_mac))
The entire error is:
Traceback (most recent call last):
File "./MAC_changer.py", line 38, in <module>
current_mac = get_current_mac(options.interface)
File "./MAC_changer.py", line 30, in get_current_mac
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
File "/usr/lib/python3.7/re.py", line 183, in search
return _compile(pattern, flags).search(string)
TypeError: cannot use a string pattern on a bytes-like object
line 38 is: options = get_arguments()
line 30 is: mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
You need to convert a byte-like object into a string, this can be done using decode method:
ifconfig_result = ifconfig_result.decode('utf-8')
In this link you can read more about converting bytes to string

Cannot concatenate 'str' and 'Nontype' objects error despite all arguments being pure string

I'm writing this python program and I'm getting this really confusing error in random. Here's part of my script:
Part of code in ai.py (starting at line #133)
elif (config.var0 < config.var1):
message = "SUCCESS_0021! var0 successfully adjusted."
print message
aux_func.write_log(message)
config.var0 = float(config.var1)
config.ask_trail = (1.0 + config.var2) * config.var3
The write_log function in aux_func.py file looks like this starting line #43
def write_log (message):
log_file = open(current_dir + '//logs//' + date_stamp(), 'a+')
temp_write = "\n " + time_stamp() + " : " + str(message)
log_file.write(temp_write)
log_file.close()
This works just fine and writes log file as expected most of the times. But, when I run this script for a while, then the console has this weird message that says:
Traceback <most recent call last):
File "main1.py", line 102, in <module>
func_flag = ai.decide()
File "C:\project\ai.py", line 137, in task_decide
aux_func.write_log(message)
File "C:\project\aux_func.py", line 45, in write_log
temp_write = "\n " + time_stamp() + " : " + str(message)
TypeError: cannot concatenate 'str' and 'NoneType' objects
The ai.py function is called from main1.py function.
I don't understand this error and I have banged my head against the wall to try and understand why I get this. The message is perfectly a string and I don't see any 'NoneType' objects in my the code where the error is being shown.
EDIT: Sorry, forgot to give you the time_stamp() code, here you go:
def time_stamp():
flag = 0
current_time = ''
system_date_time = str (datetime.datetime.now())
while (system_date_time == None):
system_date_time = str (datetime.datetime.now())
for c in system_date_time:
if (c == ' '):
flag = 1
if (c != '.'):
if (flag == 1):
current_time += c
else:
pass
else:
return current_time
It is the time_stamp() callable; it returns None.
Nothing else on that line could be None as they are either string literals, or the result of the str() function:
temp_write = "\n " + time_stamp() + " : " + str(message)
hence, the only remaining candidate is time_stamp().

Error always on line 102 of my code

So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '&center=' + common_finder(latit,longi)
else:
center = '&center=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.

Categories

Resources