python - ipaddress.py 在有效的 ip 地址上出现错误

标签 python python-2.7

我正在运行 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?

我错过了什么? 谢谢

最佳答案

来自docs :

Note that as in Python 3.3+ you must use character strings and not byte strings for textual IP address representations:

我仔细检查了一下,使用 from __future__ import unicode_literals 允许您跳过 u'make_me_unicode_string' 中的 u

>>> from __future__ import unicode_literals
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address(u'127.0.0.1')

关于python - ipaddress.py 在有效的 ip 地址上出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757401/

相关文章:

python - 罗莎琳德溶液固定: shared motifs

python - python MySQLdb 库的许可证

python - 将这个简单的 block 转换为惯用的 Python 代码

python - 为什么复制 Pandas DataFrame 后属性丢失

python - 重定向标准输出时出现 UnicodeEncodeError

python - 如何使用 Dataset API 读取变长列表的 TFRecords 文件?

python - 有什么方法可以让一个进程拥有写锁而其他进程只能并行读取?

python错误: TypeError: an integer is required

python - python 中的最大迭代项和关键属性

python - 在 Python 中将 ppt 文件转换为 pptx