Netstat Speed

DarkBlue nomail at nixmail.com
Sat Sep 2 08:20:38 EDT 2006


Sybren Stuvel wrote:

> DarkBlue enlightened us with:
>> Following code works .
> 
> No it doesn't - it's indented badly. I guess you mean something like:
> 
> def activeip(checkip):
>      # if there is any line returned we set activeb to 1 indicating that
>      # this ip is active during a netstat run
>      activeb=0
>      for line in os.popen("netstat -a -n | grep '%s'" % checkip) :
>           s=line
>          if s <>'' :
>             activeb=1
>      return activeb
> 
> Also try to use != instead of <>. Being equal or not has nothing to do
> with being larger or smaller.
> 
>> My question is can I make it faster ?
> 
> As soon as you set activeb=1, it no longer changes to any other value.
> That means that you could immediately return from that point. It's
> also cleaner to actually close an open file:
> 
> def activeip(checkip):
>      # if there is any line returned we set activeb to 1 indicating that
>      # this ip is active during a netstat run
>      activeb = 0
>      netstat = os.popen("netstat -a -n | grep '%s'" % checkip)
>      for line in netstat:
>          s = line
>          if s:
>             activeb = 1
>             break
>      netstat.close()
>      return activeb
> 
> Another way would be to let grep do the work for you. Pass it the '-q'
> option and check its exit code.
> 
> Sybren

Thank you for pointing that out.
Speed did not improve , but it definitely
is cleaner code now.

Have a nice day
Db




More information about the Python-list mailing list