Alex Lord Alex Lord - 1 year ago 99
HTML Question

Python CGI/RE Help Needed

I understand most of the following code and what it does except for the

if, line) != None:
line - which is near the bottom.

The code accepts a string input by the user on another HTML form and then this python script runs to check a file if the entered string/words is in that file and then prints all lines with the word in.

import cgi, re

print ('Content-type: text/html \n')
print ('<html>')
print ('<head>')
print ('<title>Web Client Server File Search Example </title>')
print ('</head>')
print ('<body>')
print ("<H1>Search Text Example </H1>")

form = cgi.FieldStorage()
searchString = form.getvalue('search')
print("<br><H2 style='color:red;'> Search String: ", searchString)
fh = open("animals.txt")
fhdatalist = fh.readlines()

for line in fhdatalist:
line = line.rstrip()
if, line) != None:
print ('<br>Line Found: ', line)


Could someone briefly explain how it/the search() works please?

Answer Source
searchString = form.getvalue('search')   

this line takes the search value entered in a form on the HTML page

if, line) != None:

this line takes each line in the animals.txt file and checks if the search word is found in that line. If it's found, that line from animals.txt is printed.

re is the python regular expression parser, which is extremely powerful and you should check it out!




And now, a word of warning. You are letting the viewer of your web page interact directly with your code. What if I searched for the following terms? Try it and see what happens:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download