无法在函数中创建数组

时间:2017-03-26 01:36:35

标签: python arrays function

当我运行下面的代码时,我希望变量'a'包含来自192.168.1.1-192.168.1.254的IP列表,但是当我运行'print(dir(a [:]))'时,它抛出错误:

错误:

["[IPv4Address('192.168.1.254')]"]
Traceback (most recent call last):
  File "./test.py", line 27, in <module>
    print(dir(a[:]))
TypeError: 'NoneType'

CODE:

    python3
    import ipaddress
    import csv

used_ips = []

def csv_dict_reader(file_obj):
    """
    Read a CSV file using csv.DictReader
    """
    reader = csv.DictReader(file_obj, delimiter=',')
    for line in reader:
       used_ips.append(line["ip_address"])
       print(used_ips)

def ip_list(network_addr):
   ips = []
   addr = ipaddress.ip_network(network_addr)
   for i in addr.hosts():
      ips.append([i])

if __name__ == "__main__":
    with open("data.csv") as f_obj:
        csv_dict_reader(f_obj)

a = ip_list('192.168.1.0/24')
print(dir(a[:]))

1 个答案:

答案 0 :(得分:0)

python3
import ipaddress
import csv

used_ips = []

def csv_dict_reader(file_obj):
    """
    Read a CSV file using csv.DictReader
    """
    reader = csv.DictReader(file_obj, delimiter=',')
    for line in reader:
       used_ips.append(line["ip_address"])
       print(used_ips)

def ip_list(network_addr):
   ips = []
   addr = ipaddress.ip_network(network_addr)
   for i in addr.hosts():
      ips.append([i])
   return ips

if __name__ == "__main__":
    with open("data.csv") as f_obj:
        csv_dict_reader(f_obj)

a = ip_list('192.168.1.0/24')
print(dir(a[:]))