【发布时间】:2014-08-01 13:32:18
【问题描述】:
所以,这里是代码:
#!/usr/bin/python
from sys import exit
import urllib.request
answer = urllib.request.urlopen("http://monip.org").read()
def debug(txt):
print(txt)
exit(0)
def parse_answer(answer):
''' Simple function to parse request's HTML result
to find the ip in it. Raise RuntimeError if no
ip in result and ip else.
'''
import re
pattern = "^\w+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\w+$"
regexp = re.compile(pattern)
if regexp.match(regexp, answer):
m = regexp.search(regexp, answer)
ip = m.group(0)
return ip
else:
raise RuntimeError
try:
ip = parse_answer(answer)
except RuntimeError:
print("Error, check your network configuration.")
print("Aborting..")
exit(1)
print("IP:", ip)
我写的。此代码旨在为您提供公共 IP 地址。如果它不能给你任何东西,它会抛出一个运行时错误。
这是错误:
Traceback(最近一次调用最后一次): 文件“./ippub”,第 27 行,在 ip = parse_answer(答案) 文件“./ippub”,第 19 行,在 parse_answer 如果正则表达式匹配(正则表达式,答案): TypeError: 'bytes' 对象不能被解释为整数
这意味着“答案”变量是字节,但我想在其中匹配一个 IP 地址,但我不能因为 python 类型系统:-)
有什么想法吗?非常感谢!
【问题讨论】:
标签: regex python-3.x