How do I speedup this loop?

Steve nospam at nopes
Tue Jul 13 08:48:36 CEST 2004


Hi,

I'm getting some output by running a command using os.popen. I need to 
parse the output and transform it in some sense so that it's 'DB 
compatible', (i.e I need to store the output in a database (postgres) 
after escaping some characters). Since I'm new to python, I wasn't sure 
if there was a better way of doing this so this is what I did:


             # Parse the output returned by popen and return the script
	    out = os.popen('some command')
	    all_lines = out.readlines()

             script = []
             for i in xrange(len(all_lines)):
                 line = all_lines[i].replace("'", "\\'")[0:len(line)-1] 
# replace ' with \'
                 line_without_carriage = line[0:len(line)-1] # remove 
carriage
                 line_without_carriage = 
line_without_carriage.replace("\\n", "$___n") # replace end of line with 
$___n
                 line_without_carriage += "@___n" # add a 'end of line' 
character to the end
                 script.append(line_without_carriage)
             # end for
	
             script = ''.join(script)

Please help because I'm pretty sure I'm wasting a lot of cpu time in 
this loop. Thanks

Steve




More information about the Python-list mailing list