2013-10-24 43 views
0

我试图下载剪贴板中包含的URL,但是我找不到阻止一遍又一遍下载相同页面的方法。这是我的尝试,但我得到错误TypeError: 'int' object has no attribute '__getitem__'这是什么意思?它说错误在第13行,这是它检查URL是否有效的地方。剪贴板中的Python下载URL

import time 
import os 
import urllib 

basename = "page" 
extension = ".html" 
count=0 
old_url = "" 

while(1): 
    time.sleep(1) #check clipboard every second 
    clipboard = os.system("pbpaste") # get contents of clipboard 
    if clipboard[:4] == "http" and clipboard != old_url: # check if valid URL and is diffrent 
     while os.path.exists(basename+str(count)+extension): # Create new name 
      count=count+1 
     old_url = clipboard 
     name=basename+str(count)+extension 
     data=urllib.urlopen(clipboard).read() #get page data 
     file(name, "wb").write(data) # write to file 
+0

该错误发生在哪条线上? –

+0

@ChristianTernus line 13 –

回答

1

的问题是在这条线:

clipboard = os.system("pbpaste") 

这里的原因:

In [3]: ?os.system 
Type:  builtin_function_or_method 
String Form:<built-in function system> 
Docstring: 
system(command) -> exit_status 

Execute the command (a string) in a subshell. 

使用os.system返回命令的退出状态,命令不是标准输出。

尝试subprocess模块来代替:

import subprocess 
clipboard = subprocess.check_output('pbpaste', shell=True) 

请记住,虽然,它可能为空(或少于五个字符),这将导致你的程序,当你做clipboard[:4]崩溃。最佳做法是在切片之前检查可切片对象的长度:if (len(clipboard) > 4)或更好,if (clipboard.startswith('http'))

祝你好运,快乐的编码!

+0

谢谢,我没有怀疑这是我如何阅读剪贴板的结果。 –