gpt4 book ai didi

python - 如何获取 urllib2 的上传进度条?

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:12 27 4
gpt4 key购买 nike

我目前使用以下代码将一个文件上传到远程服务器:

import MultipartPostHandler, urllib2, sys
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
params = {"data" : open("foo.bar") }
request=opener.open("http://127.0.0.1/api.php", params)
response = request.read()

这工作正常,但对于较大的文件,上传需要一些时间,如果有一个允许我显示上传进度的回调会很好吗?

我已经尝试过 kodakloader 解决方案,但它没有针对单个文件的回调。

有人知道解决方案吗?

最佳答案

这是我们的 python 依赖脚本的片段 Chris Phillips我在@ Cogi 工作过(尽管他做了这一部分)。完整的脚本是 here .

    try:
tmpfilehandle, tmpfilename = tempfile.mkstemp()
with os.fdopen(tmpfilehandle, 'w+b') as tmpfile:
print ' Downloading from %s' % self.alternateUrl

self.progressLine = ''
def showProgress(bytesSoFar, totalBytes):
if self.progressLine:
sys.stdout.write('\b' * len(self.progressLine))

self.progressLine = ' %s/%s (%0.2f%%)' % (bytesSoFar, totalBytes, float(bytesSoFar) / totalBytes * 100)
sys.stdout.write(self.progressLine)

urlfile = urllib2.urlopen(self.alternateUrl)
totalBytes = int(urlfile.info().getheader('Content-Length').strip())
bytesSoFar = 0

showProgress(bytesSoFar, totalBytes)

while True:
readBytes = urlfile.read(1024 * 100)
bytesSoFar += len(readBytes)

if not readBytes:
break

tmpfile.write(readBytes)
showProgress(bytesSoFar, totalBytes)

except HTTPError, e:
sys.stderr.write('Unable to fetch URL: %s\n' % self.alternateUrl)
raise

关于python - 如何获取 urllib2 的上传进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3241986/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com