简体   繁体   English

无缓冲的urllib2.urlopen

[英]unbuffered urllib2.urlopen

I have client for web interface to long running process. 我有用于长时间运行的Web界面的客户端。 I'd like to have output from that process to be displayed as it comes. 我想让该过程的输出在出现时显示出来。 Works great with urllib.urlopen() , but it doesn't have timeout parameter. urllib.urlopen()一起很好地工作,但是没有timeout参数。 On the other hand with urllib2.urlopen() the output is buffered. 另一方面,使用urllib2.urlopen()可以缓冲输出。 Is there a easy way to disable that buffer? 有禁用该缓冲区的简单方法吗?

urllib2 is buffered when you just call read() 当您仅调用read()时, urllib2被缓冲

you could define a size to read and therefore disable buffering. 您可以定义要读取的大小,从而禁用缓冲。

for example: 例如:

import urllib2

CHUNKSIZE = 80

r = urllib2.urlopen('http://www.python.org')
while True:
    chunk = r.read(CHUNKSIZE)
    if not chunk:
        break
    print(chunk)

this would print the response after each chunk is read from the socket, not buffer until the entire response is received. 这将在从套接字读取每个块之后打印响应,而不是缓冲直到接收到整个响应。

A quick hack that has occurred to me is to use urllib.urlopen() with threading.Timer() to emulate timeout. 我想到的一个快速技巧是将urllib.urlopen()threading.Timer()来模拟超时。 But that's only quick and dirty hack. 但这只是快速而肮脏的hack。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM