Python 3 - 从函数返回值

时间:2016-07-07 02:54:53

标签: windows python-3.x

尝试从函数返回值时收到错误 说你的dg没有定义你能说出什么问题吗?

ipl = socket.gethostbyname(socket.gethostname())
seg1,seg2,seg3,seg4=ipl.split(".")
ip2 = seg1+"."+seg2+"."+seg3+"."
ip3 = seg1+"."+seg2+"."+seg3+"."


def getDGW(ip3):
    cmd = 'ipconfig'
    p = subprocess.Popen(cmd , stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    for line in p.stdout:
        x = re.findall('Default Gateway',str(line))
        if x:
            regex = ip3 + r'[0-9]+'
            line = re.search(regex, str(line))
            if line:
                print(line.group(0))
                dg = line.group(0)
                return (dg)

getDGW(ip3)

print(dg)

1 个答案:

答案 0 :(得分:1)

您的问题不在于返回dg,而是在print(dg)语句中。您想拥有print(getDGW(ip3))

dg = getDGW(ip3)
print(dg)

dg是函数范围之外的未定义变量。