Skip to main content
 首页 » 编程设计

python之在 Python 中向后读取 URL 套接字

2024年10月17日10artech

我正在尝试从在线发布的日志文件中提取信息并通读输出。我真正需要的唯一信息发布在文件末尾。这些文件非常大,将整个套接字输出存储到一个变量并读取它会消耗大量内部内存。是否有从下到上读取套接字的方法?

我目前拥有的:

socket = urllib.urlopen(urlString) 
OUTPUT = socket.read() 
socket.close() 
OUTPUT = OUTPUT.split("\n") 
for line in OUTPUT: 
    if "xxxx" in line: 
        print line 

我正在使用 Python 2.7。我非常想从 Socket 输出的最后阅读大约 30 行。

请您参考如下方法:

在此用例中,您需要的是 HTTP Range 请求。这是我找到的教程:

http://stuff-things.net/2015/05/13/web-scale-http-tail/

我应该澄清一下:通过 Head 请求获取大小然后执行 Range 请求的优点是您不必传输所有内容。你提到你有相当大的文件资源,所以这将是最好的解决方案:)

编辑:在下面添加了这段代码...

这是该博客文章的演示(已简化),但已翻译成 Python。请注意,这不适用于所有 HTTP 服务器!内嵌更多评论:

""" 
illustration of how to 'tail' a file using http. this will not work on all 
webservers! if you need an http server to test with you can try the 
rangehttpserver module: 
 
$ pip install requests 
$ pip install rangehttpserver 
$ python -m RangeHTTPServer 
""" 
import requests 
 
TAIL_SIZE = 1024 
 
url = 'http://localhost:8000/lorem-ipsum.txt' 
response = requests.head(url) 
 
# not all servers return content-length in head, for some reason 
assert 'content-length' in response.headers, 'Content length unknown- out of luck!' 
 
# check the the resource length and construct a request header for that range 
full_length = int(response.headers['content-length']) 
assert full_length > TAIL_SIZE 
headers = { 
  'range': 'bytes={}-{}'.format( full_length - TAIL_SIZE, full_length) 
} 
 
# Make a get request, with the range header 
response = requests.get(url, headers=headers) 
assert 'accept-ranges' in response.headers, 'Accept-ranges response header missing' 
assert response.headers['accept-ranges'] == 'bytes' 
assert len(response.text) == TAIL_SIZE 
 
# Otherwise you get the entire file 
response = requests.get(url) 
assert len(response.text) == full_length