How do I speedup this loop?

Jean Brouwers JBrouwersAtProphICyDotCom at no.spam.net
Tue Jul 13 11:11:50 EDT 2004


What about handling all output as one string?

    script = os.popen('some command')
    script = script.replace("'", "\\'")  # replace ' with \'
    script = script.replace("\r", ")  # remove cr
    script = script.replace("\\n", "$___n")  # replace \n
    script = script.replace("\n", "@___n'")  # replace nl


/Jean Brouwers


In article <40f385dc$1 at clarion.carno.net.au>, Steve <nospam at nopes>
wrote:

> 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