IndexError: list index out of range Python error - python

My command line arguments:
python SearchString.py 10 nee
Argument 1 does not match the length. How should i handle that ?
Error:
File "SearchString.py", line 30, in string_search
search = temp[fieldindex]
IndexError: list index out of range
#!usr/bin/python
import sys
def string_search():
'''
This function search a string in a file through index and gives the result.
:returns: none
:return type: none
:author:XYZ
'''
if len(sys.argv) != 3:
print "Enter Two Arguments Only"
sys.exit()
stringsrch = sys.argv[2]
found = False
file_name = open("passwd", "r")
if sys.argv[1].isdigit():
fieldindex = int(sys.argv[1])-1
else:
print "Enter Integer in 1st Argument"
sys.exit()
#fieldindex = int(sys.argv[1])-1
for store_file in file_name:
temp = store_file.split(":")
search = temp[fieldindex]
if stringsrch in search:
print store_file
found = True
if not found:
print "No String "
string_search()

I think the code depends on how you use it.
search = temp[fieldindex]. From the code, your fieldindex is 9, so you should make sure len(temp) > 9. Or you will get error like what you said.

Related

Simplified grep in python

I need to create a simplified version of grep in python which will print a line when a keyword is used such as using this command "python mygrep.py duck animals.txt" and getting the output, "The duck goes quack". I have a file where it contains different outputs but I'm not sure how to get it to print the line that contains the "keyword" such as the line with "duck" in it. Im suppose to only use "import sys" and not "re" since its suppose to be a simple version.
import sys
def main():
if len(sys.argv) != 3:
exit('Please pass 2 arguments.')
search_text = sys.argv[1]
filename = sys.argv[2]
with open("animals.txt", 'r') as f:
text = f.read()
for line in text:
print(line)
if __name__ == '__main__':
main()
The operator 'in' should be sufficient.
for line in text:
if search_text in line:
print(line)
Here is a an implementation of grep in python with after/before feature:
def _fetch_logs(self, data, log_file, max_result_size, current_result_size):
after = data.get("after", 0)
before = data.get("before", 0)
exceeded_max = False
result = []
before_counter = 0
frame = []
found = False
for line in log_file:
frame.append(line)
match_patterns = all(self._search_in(data, pattern, line) for pattern in data["patterns"])
if match_patterns:
before_counter = len(frame)
found = True
if not found and len(frame) > before:
frame.pop(0)
if found and len(frame) >= before_counter + after:
found = False
before_counter = 0
result += frame
frame = []
if current_result_size + len(result) >= max_result_size:
exceeded_max = True
break
if found:
result += frame
return exceeded_max, result

Python 3 - IndexError: string index out of range

I'm currently creating a programming language in Python 3.6 and for some reason, the following code produces an IndexError: string index out of range.
When I try to execute the following code in a Windows Batch File:
#echo off
python run-file.py test.ros
pause
But I'm getting the following output:
Traceback (most recent call last):
File "run-file.py", line 16, in <module>
if not(value[1][0] == "!") and ignoreline == False:
IndexError: string index out of range
Press any key to continue . . .
The run-file.py file looks like this:
from sys import argv as args
from sys import exit as quit
import syntax
try:
args[1]
except IndexError:
print("ERROR: No ROS Code file provided in execution arguments")
print("Ensure the execution code looks something like this: python run-file.py test.ros")
with open(args[1]) as f:
ignoreline = False
content = f.readlines()
content = [x.strip() for x in content]
for value in enumerate(content):
if not(value[1][0] == "!") and ignoreline == False:
firstpart = value[1].split(".")[0]
lenoffirstpart = len(value[1].split(".")[0])
afterpart = str(value[1][lenoffirstpart + 1:])
apwithcomma = afterpart.replace(".", "', '")
preprint = str(firstpart + "(" + apwithcomma + ")")
printtext = preprint.replace("(", "('")
lastprinttext = printtext.replace(")", "')")
try:
exec(str("syntax." + lastprinttext))
except Exception as e:
template = "ERROR: An error of type {0} occured while running line {1} because {2}"
message = template.format(
type(e).__name__, str(value[0] + 1), str(e.args[0]))
print(message)
quit(1)
elif content[value[0]][0] == "!!!":
ignoreline = not(ignoreline)
quit(0)
The syntax.py file looks like this:
def print_message(contents=''):
print(contents)
The test.ros file looks like this:
! This is a single line comment
!!!
This line should be ignored
and this one as well
!!!
print_message.Hello World
The problem appears to be in line 16 of the run-file.py file:
if not(value[1][0] == "!") and ignoreline == False:
I've already tried replacing value[1][0] with (value[1])[0] and other combinations with brackets to no avail.
It seems like when I try to print the value it behaves as expected and gives me ! which is the first character of the test.ros file but for some reason, it throws an exception when it's in the if statement.
If you want any more of the source, it's on Github and you can find the exact commit containing all the files here
Update/Solution
Big thanks to Idanmel and Klaus D. for helping me resolve my issue. You can view the changes I've made here
This happens because the 2nd line in test.ros is empty.
You create content in this example to be:
['! This is a single line comment',
'',
'!!!',
'This line should be ignored',
'and this one as well',
'!!!',
'',
'print_message.Hello World']
When you try to access content[1][0], you get an IndexError because it's an empty string.
Try removing the empty lines from content by adding an if to the list comprehenssion:
content = [x.strip() for x in content if x.strip()]

#list index out of range

def isexact(pat):
for c in pat.upper():
if c not in 'ATGC':
return 0
return 1
def print_matches(ofh, enz, matches):
if matches:
print >>ofh, "Enzyme %s matches at:" % enz,
for m in matches:
print >>ofh, m,
print >>ofh
else:
print >>ofh, "No match found for enzyme %s." % enz
def get_site_only(pat):
newpat = ""
for c in pat:
if c.isalpha():
newpat += c
return newpat
def findpos(seq, pat):
matches = []
current_match = seq.find(pat)
while current_match != -1:
matches.append(current_match)
current_match =seq.find(pat, current_match+1)
return matches
seq = ""
ifh = open("C:\Python27\\link_cutzymes.txt",'r')
ofh = open("C:\Python27\\re-en-output.txt", "w")
line = ifh.readline()
while line:
fields = line.split()
name = fields[0]
pat = get_site_only(fields[2])
if isexact(pat):
print_matches(ofh, name, findpos(seq, pat))
line = ifh.readline()
else:
line = ifh.readline()
ofh.close()
ifh.close()
it is showing list index error can help me
Traceback (most recent call last): File
"C:/Users/ram/Desktop/rest_enz7.py", line 55, in
name = fields[0] IndexError: list index out of range
name = fields[0] - you probably are reading an empty line, splitting it, and accessing it at index 0, which is out of range for an empty list..
you can make sure your file contains only lines of your format, check for empty lines in the code, or use try and except to name a few options.
while reading the data from file,if data is not exist to split,it will not convert into list. I can see in your code name = fields[0] is causing error.
At that time please use try and except in your code.
you can rewrite the code as :
try:
fields = line.split()
name = fields[0]
except:
pass
What a string[x] does is get the xth letter of the list. This means that if there is no object in the xth position then you get an error.
So if name = fields[0] returns an error then fieldsmust be an empty list (It would look like this: []) because there is no first object (Python counts from zero so letter 0 is letter 1, letter 1 is letter 2 and so on). You can fix this with a try: and except: like so:
try:
name = fields[0]
except:
name = '' #Or whatever code you want to run if it fails
In the place of name = fields[0]

No output on command line python

This is my code. when I run it, it simply exits after running. There is nothing printed. Why so ?
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
if callfunc == 'initialize':
print listdir() #this will print list of files
print "\n"
for files in listdir():
checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
input.close()
found is a local name in the function checkString(); it stays local because you don't return it.
Return the variable from the function and store the return value:
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
return found
for files in listdir():
found = checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
You need to modify to:
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
input.close()
return found
found = False
if callfunc == 'initialize':
print listdir() #this will print list of files
print "\n"
for files in listdir():
found = found or checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
This is because in your original found is only in scope within the function checkString

Searching a file for matches between two values and outputting search hits in Python

I am (attempting) to write a program that searches through a hex file for instances of a hex string between two values, eg. Between D4135B and D414AC, incrementing between the first value until the second is reached- D4135B, D4135C, D4135D etc etc.
I have managed to get it to increment etc, but it’s the search part I am having trouble with.
This is the code I have so far, it's been cobbled together from other places and I need to make it somehow output all search hits into the output file (file_out)
I have exceeded the limit of my Python understanding and I'm sure there's probably a much easier way of doing this. I would be very grateful for any help.
def search_process(hx): # searching for two binary strings
global FLAG
while threeByteHexPlusOne != threeByteHex2: #Keep incrementing until second value reached
If Flag:
if hx.find(threeByteHex2) != -1:
FLAG = False #If threeByteHex = ThreeByteHexPlusOne, end search
Print (“Reached the end of the search”,hx.find(threeByteHexPlusOne))
Else:
If hx.find(threeByteHexPlusOne) != -1:
FLAG = True
Return -1 #If no results found
if __name__ == '__main__':
try:
file_in = open(FILE_IN, "r") #opening input file
file_out = open(FILE_OUT, 'w') #opening output file
hx_read = file_in.read #read from input file
tmp = ''
found = ''
while hx_read: #reading from file till file is empty
hx_read = tmp + hx_read
pos = search_process(hx_read)
while pos != -1:
hex_read = hx_read[pos:]
if FLAG:
found = found + hx_read
pos = search_process(hx_read)
tmp = bytes_read[]
hx_read = file_in.read
file_out.write(found) #writing to output file
except IOError:
print('FILE NOT FOUND!!! Check your filename or directory/PATH')
Here's a program that looks through a hex string from a file 3 bytes at a time and if the 3-byte hex string is between the given hex bounds, it writes it to another file. It makes use of generators to make getting the bytes from the hex string a little cleaner.
import base64
import sys
_usage_string = 'Usage: python {} <input_file> <output_file>'.format(sys.argv[0])
def _to_base_10_int(value):
return int(value, 16)
def get_bytes(hex_str):
# Two characters equals one byte
for i in range(0, len(hex_str), 2):
yield hex_str[i:i+2]
def get_three_byte_hexes(hex_str):
bytes = get_bytes(hex_str)
while True:
try:
three_byte_hex = next(bytes) + next(bytes) + next(bytes)
except StopIteration:
break
yield three_byte_hex
def find_hexes_in_range(hex_str, lower_bound_hex, upper_bound_hex):
lower_bound = _to_base_10_int(lower_bound_hex)
upper_bound = _to_base_10_int(upper_bound_hex)
found = []
for three_byte_hex in get_three_byte_hexes(hex_str):
hex_value = _to_base_10_int(three_byte_hex)
if lower_bound <= hex_value < upper_bound:
found.append(three_byte_hex)
return found
if __name__ == "__main__":
try:
assert(len(sys.argv) == 3)
except AssertionError:
print _usage_string
sys.exit(2)
file_contents = open(sys.argv[1], 'rb').read()
hex_str = base64.decodestring(file_contents).encode('hex')
found = find_hexes_in_range(hex_str, 'D4135B', 'D414AC')
print('Found:')
print(found)
if found:
with open(sys.argv[2], 'wb') as fout:
for _hex in found:
fout.write(_hex)
Check out some more info on generators here

Categories