注意:“代码”的第一部分不是代码,而是来自终端的错误信息,SE让我这样格式化。
使用Python 2.7.6的Linux机器
我有一个自动下载器,它应该可以获取剪贴板的内容(这个工作)并下载它们(这不工作)。以下是错误消息:
Traceback (most recent call last):
File "/home/thomasshera/Create polynomial from random sequence.py", line 6, in <module>
urllib.urlretrieve(text_in_clipboard, "/home/thomasshera/Pictures/Star Wars")
File "/usr/lib/python2.7/urllib.py", line 94, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "/usr/lib/python2.7/urllib.py", line 244, in retrieve
tfp = open(filename, 'wb')
IOError: [Errno 21] Is a directory: '/home/thomasshera/Pictures/Star Wars'
代码如下:
import Tkinter
import urllib
root = Tkinter.Tk()
root.withdraw() # Hide the main window (optional)
text_in_clipboard = root.clipboard_get()
urllib.urlretrieve(text_in_clipboard, "/home/thomasshera/Pictures/Star Wars")
使用Python shell修复这个问题很简单,除了我的程序中没有第94行之外——这个shell不知怎么错了?
首先,您看到的错误与脚本的第94行无关,而是在
urllib.py
模块中。其次,问题是如何使用
urlretrieve
方法。它接受一个URL和一个文件名。但您使用的是目录的路径,而不是文件。然后urllib
告诉你我刚才说的:请仔细阅读urllib docs。
urlretrieve
的第二个参数应该是文件的路径,而不是目录。你可以这样处理:
错误不会出现在代码中,而是出现在您使用的库中—所以您为什么会看到文件/usr/lib/python2.7/urllib.py的第94行。但原因在你的密码里。
urllib.urlretrieve
将文件名(而不是文件夹名)作为其第二个参数。(在回溯中,我们看到它被传递给期望文件名的函数open
)。这将起作用:相关问题 更多 >
编程相关推荐