2
import os
import sys
import re
import string

f=open('./iprange','r')
s=f.readline()
f.close()
pattern='inet addr:'+s
pattern=pattern.split('x')[0]
pattern='('+pattern+'...'+')'

os.system('ifconfig -a >> interfaces')
f=open('./interfaces','r')
s=f.readline()

while (len(s))!=0:
    i=re.search(pattern,s)
    if i!=None:
        sp=re.split(pattern,s)[1]
        ip=re.split('inet addr:',sp)[1]
        break
    s=f.readline()

f.close()
os.system('rm ./interfaces')
f=open('./userip','w')
f.write(ip)
f.close()

NameError;name 'ip' is not defined

I split pattern by s and store the result in sp, then I find the IP address and store the result in ip. But the error says ip is not defined - what's going on?

1
  • 1
    It's sufficient to write: while s: instead of while (len(s))!=0: because bool('') == False and bool('any_string') == True Commented Mar 5, 2013 at 16:49

2 Answers 2

3
while (len(s))!=0:
    i=re.search(pattern,s)
    if i!=None:
        sp=re.split(pattern,s)[1]
        ip=re.split('inet addr:',sp)[1]
        break
    s=f.readline()

The ip assignment is inside the if closure, which is apparently never being executed.

Sign up to request clarification or add additional context in comments.

9 Comments

I have declared ip as global still error global name ip is not defined
So how to write the value of ip in file?
ip is already global; The problem is that your while loop exists without assigning it (the search is never successful)
How to assign in while loop then?
Well, just make sure the search is successful and the if closure is executed!
|
1

I'd do something more like this:

import os
import sys
import re
from itertools import takewhile

with open('./iprange','r') as f:
    s = f.readline()

prefix = 'inet addr:'
pattern = prefix + s
pattern = pattern.split('x')[0]
pattern = '(%s...)' % pattern

os.system('ifconfig -a >> interfaces')
with open('interfaces', 'r') as f:
    # Put all lines up to the first empty line into a list
    # http://docs.python.org/2/library/itertools.html#itertools.takewhile
    # `[line.rstrip() for line in f]` could be a generator instead:
    # (line.rstrip() for line in f)
    lines = list(takewhile(lambda x: x, [line.rstrip() for line in f]))
os.remove('interfaces')

for s in lines:
    if re.search(pattern, s):
        sp = re.split(pattern, s)[1]
        ip = sp[len(prefix):]
        with open('./userip', 'w') as f:
            f.write(ip)
        break
else:
    print "No match found"

For one thing, you only write to the file userip if you find a match and you get a message if no match was found.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.