根本问题是ip_network() 实例化了一个IPv4Network/IPv6Network 对象,它要求网络地址是一个unicode 字符串。在 Python 3 中这很好,但在 Python 2 中,字符串默认不是 unicode。在 Python 2 中:
>>> import ipaddress
>>> ipaddress.IPv4Network('10.0.0.0/24')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ipaddress.py", line 1486, in __init__
self.network_address = IPv4Address(address)
File "ipaddress.py", line 1271, in __init__
self._check_packed_address(address, 4)
File "ipaddress.py", line 528, in _check_packed_address
expected_len, self._version))
ipaddress.AddressValueError: '10.0.0.0/24' (len 11 != 4) is not permitted as an IPv4 address (did you pass in a bytes instead of a unicode object?)
>>> ipaddress.IPv4Network(u'10.0.0.0/24')
IPv4Network(u'10.0.0.0/24')
ipaddress.ip_network() 捕获此异常并引发 ValueError 并带有不太详细的消息:
>>> ipaddress.ip_network('10.0.0.0/24')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ipaddress.py", line 148, in ip_network
address)
ValueError: '10.0.0.0/24' does not appear to be an IPv4 or IPv6 network
所以它看起来像一个 unicode 问题。一种可能的解释是,也许 PyCharm 正在使用 Python >= 3.3,它在标准库中提供模块 ipaddress,并且默认情况下字符串是 unicode。您的命令行 Python 可能是版本 2,其中字符串默认为字节字符串,ipaddress.ip_network() 将失败,如上所示。我不确定这一点,因为print srcIp 语句表明您在这两种情况下都使用 Python 2?
另一种可能性是 PyCharm 在某种程度上影响了 Python 2 中字符串文字的编码。我对 PyCharm 几乎一无所知,但是可以设置编码选项。也许这些有效地做了类似于from __future__ import unicode_literals 的事情。