简体   繁体   中英

file.write() in python

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM