函数中的全局命令问题

时间:2016-08-28 23:02:03

标签: python networking

我遇到了让这段代码正常运行的问题:

def ip_is_valid():
    check = False
    #Global exposes outside the local function
    global ip_list

    while True:
        #Prompting user for input
        print "\n" + "# " * 20 + "\n"
        ip_file = raw_input("# Enter IP file name followed by extension: ")
        print "\n" + "# " * 20 + "\n"

        #Changing exception message
        try:
            selected_ip_file = open(ip_file, 'r')
            #Start from the beginning of the file
            selected_ip_file.seek(0)

            ip_list = selected_ip_file.readlines()

            selected_ip_file.close()

        except IOError:
            print "\n* File %s does not exist. Please check and try again\n" % ip_file


        for ip in ip_list:
            a = ip.split('.')
            if (len(a) == 4) and (1 <= int(a[0]) <= 223) and (int(a[0]) != 127) and (int(a[0]) != 169 or int(a[1]) != 254) and (0 <= int(a[1]) <= 255 and 0 <= int(a[2]) <= 255 and 0 <= int(a[3]) <= 255):
                check = True
                break
            elif (len(a) == 4) and (224 <= int(a[0]) <= 239):
                print "\nThis is a multicast address. Please enter a unicast valid address\n"
                check = False
                continue
            elif (len(a) == 4) and (int(a[0]) == 127):
                print "\nThis is a loopback address and is not valid. Please try again.\n"
                check = False
                continue
            elif (len(a) == 4) and (int(a[0]) == 169 or int(a[1]) == 254):
                print "\n This is an APIPA address and is invalid. Please try again.\n"
                check = False
                continue
            else:
                print "\n* There was an invalid IP address. Please check and try again.\n"
                check = False
                continue

        if check == False:
            continue                
        elif check == True:
            break

ip_is_valid()

我遇到的问题是python会提示输入IP文件但是会出现以下错误:

  File ".\validip.py", line 133, in <module>
    ip_is_valid()
  File ".\validip.py", line 41, in ip_is_valid
    for ip in ip_list:
NameError: global name 'ip_list' is not defined

即使我在函数中定义了ip_list,我仍然会收到该错误。我正在使用&#34; global&#34;因为此程序中还有其他功能需要可见IP列表变量。

def create_threads():
    threads = []
    for ip in ip_list:
        th = threading.Thread(target = open_ssh_conn, args = (ip,)) 
        th.start()
        threads.append(th)
    for th in threads:
        th.join()

create_threads()

1 个答案:

答案 0 :(得分:2)

在将变量ip_list用作global变量之前,必须在外部范围内定义它。例如,在您的情况下,您可以像以下一样运行:

ip_list = []
def ip_is_valid():
    # Some logic
    global ip_list
    # Some more logic

或根据您需要的位置ip_list定义它。

PS :在调用ip_list函数

之前,您必须定义ip_is_valid