我正在运行 python 2.7。我下载了 ipaddress.py ( https://github.com/phihag/ipaddress )的原始文件。我试图运行一个测试来验证每个示例的 IP 地址。但即使是有效的 IP 地址似乎也无效。
>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ipaddress.py", line 163, in ip_address
' a unicode object?' % address)
ipaddress.AddressValueError: '127.0.0.1' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?
>>> ipaddress.ip_address('192.168.0.1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ipaddress.py", line 163, in ip_address
' a unicode object?' % address)
ipaddress.AddressValueError: '192.168.0.1' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?
Run Code Online (Sandbox Code Playgroud)
我错过了什么?谢谢
从文档:
请注意,在 Python 3.3+ 中,您必须使用字符串而不是字节字符串来表示文本 IP 地址:
我仔细检查了一下,使用from __future__ import unicode_literals
允许你跳过u
in u'make_me_unicode_string'
。
>>> from __future__ import unicode_literals
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address(u'127.0.0.1')
Run Code Online (Sandbox Code Playgroud)