gpt4 book ai didi

python - 如何修复 ValueError : read of closed file exception?

转载 作者:太空狗 更新时间:2023-10-29 21:06:04 31 4
gpt4 key购买 nike

这个简单的 Python 3 脚本:

import urllib.request

host = "scholar.google.com"
link = "/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0"
url = "http://" + host + link
filename = "cite0.bib"
print(url)
urllib.request.urlretrieve(url, filename)

引发此异常:

Traceback (most recent call last):
File "C:\Users\ricardo\Desktop\Google-Scholar\BibTex\test2.py", line 8, in <module>
urllib.request.urlretrieve(url, filename)
File "C:\Python32\lib\urllib\request.py", line 150, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "C:\Python32\lib\urllib\request.py", line 1597, in retrieve
block = fp.read(bs)
ValueError: read of closed file

我认为这可能是一个暂时的问题,所以我添加了一些简单的异常处理,如下所示:

import random
import time
import urllib.request

host = "scholar.google.com"
link = "/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0"
url = "http://" + host + link
filename = "cite0.bib"
print(url)
while True:
try:
print("Downloading...")
time.sleep(random.randint(0, 5))
urllib.request.urlretrieve(url, filename)
break
except ValueError:
pass

但这只会无限期地打印Downloading...

最佳答案

您的 URL 返回 403 代码错误并且显然是 urllib.request.urlretrieve不善于检测所有 HTTP 错误,因为它使用 urllib.request.FancyURLopener最新的尝试通过返回 urlinfo 而不是引发错误来吞下错误。

关于如果您仍想使用 urlretrieve 的修复您可以像这样覆盖 FancyURLopener(包含的代码也显示错误):

import urllib.request
from urllib.request import FancyURLopener


class FixFancyURLOpener(FancyURLopener):

def http_error_default(self, url, fp, errcode, errmsg, headers):
if errcode == 403:
raise ValueError("403")
return super(FixFancyURLOpener, self).http_error_default(
url, fp, errcode, errmsg, headers
)

# Monkey Patch
urllib.request.FancyURLopener = FixFancyURLOpener

url = "http://scholar.google.com/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0"
urllib.request.urlretrieve(url, "cite0.bib")

否则这就是我推荐你可以使用的urllib.request.urlopen像这样:

fp = urllib.request.urlopen('http://scholar.google.com/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0')
with open("citi0.bib", "w") as fo:
fo.write(fp.read())

关于python - 如何修复 ValueError : read of closed file exception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531617/

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