Diving right in: Auto-save clipboard contents in Windows

09Sep08

Hello boys and girls, and welcome to Everyday Scripting, a blog about how you can use modern scripting technologies to improve your everyday life!

“But Ken,” you might ask, “why do I need to know how to script things? Isn’t that programming?”

Well yes, it is. Programming isn’t just for the guys at Google and Microsoft, though — thanks to modern, high-level languages like Python, Ruby, Perl and a whole host of others, most of us can learn how to automate certain tasks.

Of course I don’t expect you to take my word as gospel here, so let’s dive right into our first example. Using Python, we’re going to create a script to automatically save anything you’ve copied to your clipboard (which is what happens when you hit control-c or right-click and hit “copy”) into a text file on your desktop.

First, the code:

import win32clipboard as w
from datetime import datetime

w.OpenClipboard()
d=w.GetClipboardData(w.CF_TEXT)
w.CloseClipboard()

f = open(“C:/Documents and Settings/YOUR-USER-NAME/Desktop/” + datetime.strftime(datetime.now(), “%d-%m-%y_%H%M%S”) + “.txt”, “w”)
f.write(d)
f.close()

(Sidenote: Why did I use a blockquote there instead of a code tag? Because WordPress apparently won’t continue a code tag if there’s a blank line…so my choice is to either leave it unreadable and use code tags, or break it up and use a blockquote; sorry.)

That’s it. Eight lines of code, and two of those to import the proper libraries. Now, how do you get it to run, and furthermore, what does any of that mean?

Well, let’s get it running first. You will need to do a bit of legwork on your own at this point, because I’m not here to help you get Python set up and running on your computers. Head to the official Python Web site and download a copy of Python 2.5 for Windows. To set Python up so that you can double-click on a file and have it run, check out the Windows FAQ.

Once you’ve done that, you’ll need to download and install one more thing, the pywin32 library, which is the code we call to actually grab the clipboard contents. A library is simply a bunch of reusable code we can call in our own programs that other developers have made available to us. In this case, Mark Hammond has been nice enough to supply us with the pywin23 library, which allows us to read the Windows clipboard, among other things.

Now, let’s step through the code. As I’ve said previously, the first two lines simply import libraries we need:
import win32clipboard as w
from datetime import datetime

In this case, we import the win32clipboard library as “w”, so that we don’t need to type the whole thing out. This is one of those cool things about Python: you can set aliases for anything you import.

The second line may seem a bit more confusing, but there is a datetime class within the module datetime, so instead of importing the datetime module and having to type datetime.datetime.now() later in the code, we import just the class we need.

The next three lines come almost verbatim from a post on ActiveState’s Python Cookbook.

w.OpenClipboard()
d=w.GetClipboardData(w.CF_TEXT)
w.CloseClipboard()

This should make sense to you, even if you aren’t much of a coder. We use the OpenClipboard() function from Mark Hammond’s library, then we call the GetClipboardData() function, specifying that we want text. The result of that function gets stored in the variable “d”. We then close the clipboard for good measure. It’s good programming practice in every language — even one like Python that manages memory for you — to close resources after you open them.


f = open(”C:/Documents and Settings/kschwencke/Desktop/” + datetime.strftime(datetime.now(), “%d-%m-%y_%H%M%S”) + “.txt”, “w”)
f.write(d)
f.close()

Now, here we open a file on the Desktop (though you can modify it to go wherever you want). You can see in this snippet I’ve modified it to use my own user name — be sure to change it to yours in the actual code.

The first line may seem a little crazy at first, but let’s take a closer look:
”C:/Documents and Settings/kschwencke/Desktop/” + datetime.strftime(datetime.now(), “%d-%m-%y_%H%M%S”) + “.txt”

It simply takes the directory where your Desktop is located, and appends (using the plus sign) the current date and time formatted in a specific way. If you’re interested, you can see all of the options for the strftime() function. I use a day-month-year numeric format, followed by the hour, minutes and seconds, followed by the general text file extension (“.txt”).

If you’ll reference the code again, you see the “w” option specified to the open() function — this just tells the function to open a file in “write” mode.

The next two lines seem self-explanatory: we write the contents of “d” (your clipboard contents) out to the file, and close it back up.

That’s it. Save the file as “clipsave.py” anywhere you want, and add it to your Quick Launch Bar. Now when you copy some text, click on the icon. Presto! You should have a file on your desktop named with the date and time, filled up with whatever you’ve copied.

I hope you enjoyed the first installment of Everyday Scripting. If you’ve found this post useful, think I’m an idiot, have any questions or just want to say hello, drop me a line in the comments.

Advertisements


5 Responses to “Diving right in: Auto-save clipboard contents in Windows”

  1. 1 Angie

    I am not a coder, though I would like to be one. This is interesting. Are there any tricks to installing Python and the pywin32 library?

  2. 2 schwanksta

    Hi Angie,

    None that I am aware of. The Python installer should run almost automatically; just make sure that you get the version of pywin32 made for your Python version.

    For example, if you download version 2.5.2, which is the most recent version of the 2.5 branch of Python, you must also download the pywin32 library made for version 2.5. They are all listed on the download page.

    Hope that helps,

    -Ken

  3. Nice first post, Ken. Have you seen that an updated version of the e-book Byte of Python is out and updated for Python 3.0? I haven’t looked at the updated text, but the original for Python 2.x is great — very manageable chunks and flow I think would suit code rookies.

    I’ve looked at quite a few texts, and this is the one I think I’d use if I were teaching a course (at least in the journalism college). I doubt you want to spend a lot of your blog effort going over the nuts and bolts of numbers, strings and other data structures.

    Take a peek, and let me know what you think.


  1. 1 Backtracking a bit: « Everyday Scripting
  2. 2 First contact: Downloading from the Internet « Everyday Scripting

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: