Domanda

I am trying to download the URL that is contained in the clipboard, but i can not find a way to prevent downloading the same page over and over again. This is what i tried, but i get the error TypeError: 'int' object has no attribute '__getitem__' what does this mean? it say that the error is on line 13, this is where it checks to see if the URL is valid.

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
È stato utile?

Soluzione

The problem is on this line:

clipboard = os.system("pbpaste")

Here's why:

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 returns the exit status of the command, not the stdout of the command.

Try the subprocess module instead:

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

Bear in mind, though, that it may be blank (or have less than five characters), which will cause your program to crash when you do clipboard[:4]. Best practice is to check the length of a sliceable object before slicing it: if (len(clipboard) > 4), or better yet, if (clipboard.startswith('http')).

Good luck and happy coding!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top