IndexError: list index out of range from client side - python

Happy Friday. This puzzle is really a pain in my neck, any advice will be appreciated. Thanks a ton.
I am on Python 2.7 with Windows 7.
I send a piece of command to device via model-client model (im at client side) and wait for a response (charging status) from device. Then I would like to extract some value from the list of return. And BANG! Error pops out! "IndexError: list index out of range".
My Python code is in below:
def chrg_Test():
try:
self.s.send(getchar)
time.sleep(2)
except:
print 'Chrg cmd sent failed...'
print 'Start Chrg Test...'
result = self.s.recv(1024)
time.sleep(3)
ExtPwrPresent = (result.split('\n'))[11]
print 'ExtPwrPresent is: ', ExtPwrPresent
chrg_Test()
And the Error is:
ExtPwrPresent = (result.split('\n'))[11]
IndexError: list index out of range
Some other details: what is wired is , the error pops out like 50% or more. And rest time it works good. So it got some temper and on and off randomly which is like an annoying babe~ The correct output should be like:
Result list is:
getchar
Label,Value
FuelPercent,31
BatteryOverTemp,0
ChargingActive,0
ChargingEnabled,0
ConfidentOnFuel,0
OnReservedFuel,0
EmptyFuel,0
BatteryFailure,0
ExtPwrPresent,0
ThermistorPresent,1
BattTempCAvg,23
VBattV,14.42
VExtV,0.00
Charger_mAH,0
Discharge_mAH,200
ExtPwrPresent is: ExtPwrPresent,0
So far, the solution I tried is - turn off the server socket and turn it on again, then run this client code. It works most time, but I think it is just a temporary way, I bet there is some better way to solve it.

Related

Struggling reading data from UART

I've started programming in Python just recently but I've come over my first issue and that is:
uart.readline()
I'm sending multiple lines of data over UART to control my LED lights at home, so my idea is to send something like "r255", "g255", "b255", "br5". The format of the data being sent is not important to me, important is to get red, green, and blue values between 0-255 and a brightness value between 1-10 and somehow decode and process the data in Python. Btw. I'm sending the data from my Android App, the formatting and everything on that end should be fine.
But to the problem. I have a code as follows:
uart = UART(0,9600)
while True:
if uart.any():
data = uart.readline()
print(data)
This returns something like this for the red value:
b'r'
b'2'
b'5'
b'5'
That's fine to me and I understand why that is happening. I can probably work out how to put the data together so they make sense and work with them but the problem is that each line is actually going through another cycle so I can't really do any operations in the while loop to get the data together, or can I?
If I try something like this:
while True:
if uart.any():
data = uart.readline()
data2 = uart.readline()
data3 = uart.readline()
print(data)
print(data2)
print(data3)
I get:
b'r'
None
None
What is a solution to this problem? Am I missing something really obvious? Why can't I read more than one line in that loop? Why does the loop always have to repeat to read another line? How do I approach this in order to get the data together? I've tried uart.read() but it always returns something else like b'red2' b'55' or b'red255' or b'red' b'255' so it's even more mess and too much for me to understand what's happening there.
I can't test this for obvious reasons, but this should correct the problem of not calling uart.any() before each uart.readline(). I defined a separate function to do that and call it multiple times.
import time
import uart
def read_line():
while not uart.any():
time.sleep(0.0001)
return uart.readline()
while True:
lines = [read_line() for _ in range(3)] # Read 3 lines.
print(b''.join(lines)) # Join them together.

Controls computer keyboard through pyserial

I don't know how to use regular expression in a pile of code and I'm not sure how to code it correctly either. I tried to lookup for tutorial, guides, everything. But I'm still not understand about it, so please help me to fix my stupid code.
Summary of the working, I'm trying to code a small program that controls my computer keyboard through pyserial and with the help of microbit. For example, when button A is pressed, the microbit sends data to my computer through uart and my python shell at the end receiving the message, try to match it and execute the respective command.
This is the code of microbit
from microbit import *
uart.init(baudrate=57600, bits=8, parity=None, stop=1, tx=None, rx=None)
while True:
if button_a.is_pressed():
uart.write("Up")
display.show(Image.ARROW_NW)
if button_b.is_pressed():
uart.write("Down")
display.show(Image.ARROW_S)
else:
display.show(Image.ASLEEP)
This is the code of my python end
import re
import serial
import keyboard
serialPort = serial.Serial(port = "COM5", baudrate=57600,
bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
serialString = ""
while(1):
(serialPort.in_waiting > 0)
serialString = serialPort.readline()
wordsa = ("up")
wordsb = ("down")
if():
words = [word.lower() for word in wordsa if re.match('^[a-zA-Z]+', word)]
keyboard.press_and_release('up')
The problem is I want to have re to match the string or data received from microbit through uart at serialString = serial.Port.readline(), if the microbit sends UP, I would want python to match the data received is UP or Down, then press the keyboard key UP or DOWN respectively. Upon running this shitty code of mine, there are no errors showing up and it won't work at all. I think this is a very stupid question to ask, but please help me. This problem has burned a hole at my brain already.
Thank you and Kudos to DarryIG, Profile Link. He saved my days
If any beginners like me just wanting to do a match-up on a string.
You don't need to use regular expression. You can do it with operator == while = is assignment.
For example:
Game = ['Dota2', 'LoL']; #Games that you play
Like = ['Dota2', 'LoL']; #Games that your friend likes
if Game == Like:
print ('True')
else:
print ('False')
Output : True
Note: I know my answer sucks, but I just wanna keep this question answered just in case someone like me will need this information. Thanks for understanding.

PyGtk text buffer using to much memory want to clean it but then iter dont work

So I am just learning how to code and Im using pygtk to make a gui for a irc bot that im working on. The bot as some fun commands and stuf, but what im really here for is that I print the chat messages into a textbuffer and it makes memory go up, wich really isnt a problem unless you have a huge ammount of messages or want this to be on all the time. But with this problems in mind I wanted the bot to when he reached like 500 messages in the textbuffer(or 500 lines) he would delete the first 250 from the text buffer so that it would keep the memory usage down and still plenty of messages to read to whoever was using the gui.
My problem is that I dont really know how to do this, if I use iters they will become useless when delete the 250 lines because i've changed the textbuffer, and I also tried to use marks but it does look like I know how to use them...
HALP PLOX! xD
Code can be found here. The textbuffer is located inside run.py and is named chatbuffer.
Solved it Kappa
I use this for deletion:
if chatbuffer.get_line_count() > 10:
chatbuffer.delete(chatbuffer.get_iter_at_line(0), chatbuffer.get_iter_at_line(251))
And instead of defining inters like:
end_inter = chatbuffer.get_end_inter()
I just straigth up use:
chatbuffer.get_end_inter()
Like this:
chatbuffer.insert(chatbuffer.get_end_iter(), user + " > " + message + "\n")
EDIT: WELL IM DUMB I created a whole another questin because of an error that I encouuntered after this because I tested this with 10 lines and deleting 5 and forgot to change it to 500 on the final code. gtk-error **: gtk_text_btree_previous_line ran out of lines aborting

extracting ip address from raw_input

I have compiled a script in python 2.6.5, The script is simply to automate my most used functions for nmap and log the output to a txt file on the desktop.
I haven't written this all myself as i am still only learning python. I found an update script for updating backtrack and used that as a template for indentation and commands and modified it and added some of my own stuff to give me what i needed.
The problem i'm having is with this block
def nmap_target():
try: ip = raw_input(" [>] Enter ip to scan: ")
except KeyboardInterrupt:
print "\n [>] Exiting!\n"
sleep(1)
sys.exit()
print " [>] Attempting targeted scan.\n"
#print ip
if subprocess.Popen("nmap ip >> //root/Desktop/Target.txt && tail /root/Desktop/Target.txt",shell=True).wait() == 0:
print "\n"
print " [>] Targeted scan completed successfully!\n"
menu_main()
else:
print "\n"
print " [>] Nmap scan failed.\n"
The idea behind it is that it asks the user to input an ip address into raw_input() and call it ip, I'm trying to then pass it to nmap using subprocess.Popen("nmap ip as can be seen above.
The problem is its just writing nmap ip rather than printing the ip address and then returning errors, It even tries to scan out of my network, every time i test it i make sure the internet cable is unplugged from my router, This causes a bug with my internet test though, so if you try running the code bellow you may need to hash out the internet_check() option in the menu_main() section if you have your internet unplugged from the router
I have spent 4 days on this now and its driving me mad, At first i thought i needed to convert the number to floating point so i tried that and still the same, I've tried all sorts of things and spent hours trawling the internet looking for an answer to no avail.
I am now convinced its not the command i'm trying that is to blame i think it is the exit statement, I have tried putting "print ip" right after the line where it says "print " [>] Attempting targeted scan.\n" and sure enough the ip address that was entered is displayed on the screen, That proved to me that raw_input() is working. As soon as i move it anywhere bellow that it fails, This suggests to me that it must be either a problem with the exit statement or maybe indentation, I'm not sure though.
I have also tried hashing out the keyboard interrupt as well as the couple of lines bellow, i tried moving the try: and if statements around and even tried other commands instead but it just wont work aaaarrrrrgggghhhhhh
Would i be right in thinking that the ip is being entered into raw_input() and then the file ip that was created that holds the ip address is being destroyed before i can pass it to subprocess.Popen("nmap ip.
Like i mentioned i didn't write this script from scratch and this is my first project like this so i've got a lot to learn, I've been all through the python man pages and looked through all sorts of tutorials but just can't figure this out.
Any help will be much appreciated
i will post the full script if anyone is interested,just as soon as i can figure out how to post code properly
You need to seperate the variable from the string! Try this :D
if subprocess.Popen('nmap '+ip+' >> //root/Desktop/Target.txt && tail /root/Desktop/Target.txt',shell=True).wait() == 0:
Hope it helps!
EDIT - If for some reason python takes the raw input as an integer, convert it to string like so:
if subprocess.Popen('nmap '+str(ip)+' >> //root/Desktop/Target.txt && tail /root/Desktop/Target.txt',shell=True).wait() == 0:
Python doesn't like to concatenate str and int types, or so it tells when my script fails :P I am pretty sure your ip variable will be str type though so the first example should work.
Cheers!
You need to format the string properly or the string ip won't be interpreted at all, i.e. it won't get replaced wth the actual IP. Try something like:
cmd = "nmap ${0} >> [....] root/Desktop/Target.txt".format(ip)
if subprocess.Popen(cmd):
You could also use the % operator:
cmd = "nmap %s >> [....] root/Desktop/Target.txt" % ip

Random.choice pulling entire list, instead of single items

I am (continually) working on a project with gmail and imaplib. I am searching gmail for emails that contain a specific word, and receiving a list of unique ids (most of my code is based off of/is Doug Hellman's, from his excellent imaplib tutorial). Those unique ids are saved to a list. I am trying to pull a single id from the list, but random.choice keeps pulling the entire list. Here is the code:
import imaplib
import random
from imaplib_list_parse import parse_list_response
c = imaplib_connect.open_connection()
msg_ids = []
c.select('[Gmail]/Chats', readonly=True)
typ, msg_ids = c.search(None, '(BODY "friend")')
random_id = random.choice(msg_ids)
print random_id
I've messed around in the interpreter and msg_ids is definitely a list. I've also attempted to pull specific elements of the array (ex: msg_ids[1] etc) but it says "IndexError: list index out of range" which I understand to mean "the thing you are looking for isn't there", which is confusing because it is there.
Is there anytime a list is not a list? Or something? I'm confused.
As always, I appreciate any feedback the wonderful people of stackoverflow could give :)
I think random_id is a list of list, something like: [[1,2,3,5]]。So when you call msg_ids[1], it raise IndexError. And since there is only one element in the list, random.choice() always return the element. You can try:
print random.choice(msg_ids[0])
To debug this kind of things, you can try print the random_id, or use IPython to interactive your code to find out the problem.

Categories