Python Forum

Full Version: HTML+CGI (if __name__ == '__main__')
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I am new to Python + CGI. my application is to searching multiple file using parallel processing. each process return the output any time. I want to process that ourput and place in HTML table. here is mycode.
what I abserved the html table is updating proper if print before "if __name__ == '__main__':".

Can you point me what is the mistake in the script?


Top CGI (page.cgi):
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
print ("Content-type:text/html\r\n\r\n");
print ('');

print ('<html>');
print ('<form action = "./searchEngine.cgi" method = "post">');
print ('First Name: <input type = "text" name = "first_name">  <br />');
print ('Last Name: <input type = "text" name = "last_name" />');
print ('<input type = "submit" value = "Submit" />');
print ('</form>');
print ('</html>');
searchEngine.cgi:
#!/usr/bin/python

import multiprocessing as mp
import re
import os
import sys
import linecache
import cgi, cgitb
cgitb.enable()

results = [];
# Create instance of FieldStorage 
#form = cgi.FieldStorage() 

# Get data from fields
#first_name = form.getvalue('first_name')
#last_name  = form.getvalue('last_name')

def FileSearch(fileName,pattern):
    fName = "";
    lineNo = "";
    regNam = ""
    f = open(fileName,"r+" )
    for lines in f.readlines():
        matchObj = re.search(pattern,lines)
        regName = re.search("^time",lines)
        fileN = re.search("^[place]",lines)
        st = str.split(lines,":");
        if regName:
            regN = len(st);
            regNam = st[regN-1];
        if fileN:
            fileNN = len(st);
            fName = st[fileNN-2];
            lineNo = st[fileNN-1];
        if matchObj:
            lineNo = int(st[0]);
            tp = linecache.getline(fName,lineNo);
            return(regNam.strip() ,fName.strip(),st[0],tp.strip());
    f.close();

def collect_result(result):
        global results
        sd = result;
        if sd != None:
            results.append(result);
            print('<tr> <td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % ( sd[0], sd[1],sd[2],sd[3]));   [b[i]]#### this print is not working[/i]….[/b]

def main():
     ### print('<tr> <td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % ( sd[0], sd[1],sd[2],sd[3]));   ## this is working
    if __name__ == '__main__':
        global results;
        pool = mp.Pool(mp.cpu_count());
        f = open("./list","r" );
        data = f.readlines();
        pool = mp.Pool()
        for i, row in enumerate(data):
            pool.apply_async(FileSearch,args=(row.strip(),"name"), callback=collect_result);
        pool.close();
        pool.join();  # Wait for all subprocesses to finish.
        f.close();
        for sd in results:
            if sd != None:
                print("<tr> <td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % ( sd[0], sd[1],sd[2],sd[3]));


def htmlHead():
    print ("Content-type:text/html\r\n\r\n");
    print ('');
    print('<html>');
    print('<head>');
    print('<title>Python CGI test</title>');
    print('</head>');
    print('<body>');
    print('<table id="myTable1" border = "1" width = "35%" style="margin-top:10px; margin-left:100px;">');
    print('<tr>');
    print('<th id=100> Name </th>');
    print('<th id=101> Place </th>');
    print('<th id=102> Time </th>');
    print('</tr>');

def htmlTail():
    print('</table>');
    print('</body>');
    print('</html>');

htmlHead();
main();
htmlTail();
You need to move the "if __name__=="__main__"part, it needs to go at the bottom of the code:

if __name__=="__main__":
    htmlHead()
    main()
    htmlTail()
Also, you never appear to call def collect_result(result): and I think you maybe need to split the searching code and the page making code.
Hi Mariendbad,
Thanks for reply. I have tried you step and it's not working.

BTW, collect_result is called in :
for i, row in enumerate(data):
pool.apply_async(FileSearch,args=(row.strip(),"name"), callback=collect_result);

Thanks,
Mahesh
You have commented out the lines where it gets the actual form data:

# Create instance of FieldStorage
    #form = cgi.FieldStorage()

    # Get data from fields
    #first_name = form.getvalue('first_name')
    #last_name = form.getvalue('last_name')
Does uncommenting these change things?

Also, what does the file it searches look like?
Hi Marienbad,
Idea is to pass file name which has list of file in "file_name" text and pass pattern in "last_name".
In this has, below is the format of the list, and other files. it will search " name, time, place" and update in table.
you can use below files...
%cat list
file1
file2
file3

%cat file1
name: Mahesh
time: 20.20
place: Office

%cat file2
name: Mahesh2
time: 20.22
place: Office2

%cat file3
name: Mahesh3
time: 20.23
place: Office3
I re-wrote the FiloeSearch method like this:

	def FileSearch(fileName,pattern):
		name_line = ""
		time_line = ""
		place_line = ""
		name, time, place = None;
		
		with open(fileName, "r+") as f:

		for line in f.readlines():
			name_line = re.search(pattern,lines)
			time_line = re.search("^time",lines)
			place_line = re.search("^[place]",lines)

			st = str.split(line,":")
			if name_line:
				name = st[1]
			
			if time_line:
				time = st[1]
				
			if place_line:
				place = st[1]
				

	##### I am not sure what you are doing here.... but your table only has 3 headings and you are sending 4 values back so I think you can get rid of the line number stuff
	### f.close(); done automatically by using with open()
		
		return(name, time, place)
	
You have 4 values being returned but are only using 3 of them. What results are you getting back when you run your code?
(Feb-19-2019, 11:49 AM)mahesh Wrote: [ -> ]Hi, I am new to Python + CGI.
You should not be using CGI,Python has left that old technology behind and written own solution WSGI.
Look at this post where i explain better.