473,774 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

urllib2.urlopen Progress bar

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

In urllib.urlretri eve I can use reporthook to implement a progress bar.

But in urllib2.urlopen I can't.
I have to use urllib2.urlopen because it throws exceptions which are
important to be handled where as urlretrieve is dumb.

Is there a way to implement urllib2.urlopen to enable reporthook ?

progress.py code:

#!/usr/bin/env python

import time, urllib2, urllib

class progressBar:
def __init__(self, minValue = 0, maxValue = 10, totalWidth=12):
self.progBar = "[]" # This holds the progress bar string
self.min = minValue
self.max = maxValue
self.span = maxValue - minValue
self.width = totalWidth
self.amount = 0 # When amount == max, we are 100% done
self.updateAmou nt(0) # Build progress bar string

def updateAmount(se lf, newAmount = 0):
if newAmount < self.min: newAmount = self.min
if newAmount > self.max: newAmount = self.max
self.amount = newAmount

# Figure out the new percent done, round to an integer
diffFromMin = float(self.amou nt - self.min)
percentDone = (diffFromMin / float(self.span )) * 100.0
percentDone = round(percentDo ne)
percentDone = int(percentDone )

# Figure out how many hash bars the percentage should be
allFull = self.width - 2
numHashes = (percentDone / 100.0) * allFull
numHashes = int(round(numHa shes))

# build a progress bar with hashes and spaces
self.progBar = "[" + '#'*numHashes + ' '*(allFull-numHashes) + "]"

# figure out where to put the percentage, roughly centered
percentPlace = (len(self.progB ar) / 2) - len(str(percent Done))
percentString = str(percentDone ) + "%"

# slice the percentage into the bar
#self.progBar = self.progBar[0:percentPlace] + percentString +
self.progBar[percentPlace+le n(percentString ):]
self.progBar = self.progBar[0:percentPlace] +
self.progBar[percentPlace+le n(percentString ):] + percentString

def __str__(self):
return str(self.progBa r)

def myReportHook(co unt, blockSize, totalSize):
import sys
global prog

if prog == "":
prog = progressBar(0,t otalSize,50)
#print count, blockSize, totalSize
#prog = progressBar(0, totalSize, 77)
prog.updateAmou nt(count*blockS ize)
sys.stdout.writ e (str(prog))
sys.stdout.writ e ("\r")
#print count * (blockSize/1024) , "kb of " , (totalSize/1024) , "kb
downloaded.\n"
prog = ""
sFile = "new.rpm"
sUrl="http://localhost/new.rpm"
urllib.urlretri eve(sUrl, sFile, reporthook=myRe portHook)
print "\n\n"
#temp = urllib2.urlopen (sUrl)
#lastval = int(temp.header s['Content-Length'])
#prog = progressBar(0, lastval, 77)
#
#for x in range(101):
# prog.updateAmou nt(x)
# print prog, "\r", time.sleep(0.5)
#
#data = open(sFile,'wb' )
#data.write(tem p.read())
#data.close()
#temp.close()
Regards,
Ritesh
- --
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
Gnupg Key ID: 04F130BC
"Stealing logic from one person is plagiarism, stealing from many is
research."
"Necessity is the mother of invention."
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFDyfkM4Rh i6gTxMLwRAlmMAJ 9yePv6DvXCcnUb0 DYhWSuIonciSACg rxDj
aKSGkfg8I1T/q3r6zWLTXmw=
=uomB
-----END PGP SIGNATURE-----

Jan 15 '06 #1
0 2533

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6118
by: John F Dutcher | last post by:
Can anyone comment on why the code shown in the Python error is in some way incorrect...or is there a problem with Python on my hoster's site ?? The highlites don't seem to show here...but line #80 and line # 38 are the first line offenders. --> --> -->
5
7410
by: Pascal | last post by:
Hello, I want to acces my OWA (Outlook Web Acces - http Exchange interface) server with urllib2 but, when I try, I've always a 401 http error. Can someone help me (and us)? Thanks. here's my pyscript:
0
4977
by: Matt | last post by:
I'm trying to get the HTML data off of a webpage. Let's say for the sake of argument it's the python homepage. I've googled around and found some examples that people said worked. Here's what I've cobbled together: #getHTML.py ############################################ import urllib import urllib2 proxy_info = {'user':'us3r',
0
1863
by: Gil Tal | last post by:
Hi, I use urllib2 to download a redirected url and I get an exception from the bowels of urllib2. It seems that urllib2 implements some super sophisticated self check and tries to control the access to attributes using lots of calls to hasattr(the builtin function) and a custom __getattr__() on the Request class that perfroms some checks and raises an AttributeError if it's not happy. The problem is that hasattr() according to the docs is...
0
2450
by: Ali.Sabil | last post by:
hello all, I just maybe hit a bug in both urllib and urllib2, actually urllib doesn't support proxy authentication, and if you setup the http_proxy env var to http_proxy=http://user:passwd@host:port/ and https_proxy=$http_proxy i get a traceback : Traceback (most recent call last): File "test_urllib.py", line 2, in ? urllib.urlopen("https://sf.net/")
1
5760
by: Alessandro Fachin | last post by:
I write this simply code that should give me the access to private page with htaccess using a proxy, i don't known because it's wrong... import urllib,urllib2 #input url url="http://localhost/private/file" #proxy set up
10
4168
by: rplobue | last post by:
im trying to get urllib2 to work on my server which runs python 2.2.1. When i run the following code: import urllib2 for line in urllib2.urlopen('www.google.com'): print line i will always get the error:
1
4840
by: est | last post by:
A simple py script import urllib2 req=urllib2.Request("http://www.google.com") req.set_proxy("127.0.0.1:1","http") print urllib2.urlopen(req).read()
1
3373
by: Magnus.Moraberg | last post by:
Hi, I have the following code - import urllib2 from BeautifulSoup import BeautifulSoup proxy_support = urllib2.ProxyHandler({"http":"http:// 999.999.999.999:8080"}) opener = urllib2.build_opener(proxy_support)
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8939
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.