python中的file.write()

时间:2013-03-05 16:34:41

标签: 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

我将pattern拆分为s并将结果存储在sp中,然后找到IP地址并将结果存储在ip中。但错误说ip未定义 - 发生了什么?

2 个答案:

答案 0 :(得分: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()

ip赋值在if闭包内,显然从未执行过。

答案 1 :(得分:1)

我会做更多这样的事情:

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"

首先,如果找到匹配项,您只会写入文件userip,如果找不到匹配项,则会收到消息。