05 December 2008

Python is Your Friend

I said I'd mention when I wrote twitter scripts and true to my word here's the first script I've written to interact with twitter. I was quite surprised to not find a command-line twitter client in the Ubuntu repositories, but perhaps it's because python makes it so easy:
#!/usr/bin/python
import twitter
from sys import argv
api = twitter.Api(username='askForCharon', password='redacted')
status = api.PostUpdate(argv[1])
api.ClearCredentials()

There's the entirety of my script. It knows my credentials (although I'm loathe to write anything that stores a password in plaintext) and takes the message to tweet on the command line. A slightly more sophisticated version would include a check to make sure the message was <= 140 characters. I wrote this for clinic, actually. I was getting ready to start a long-running job and I wanted to be alerted when it finished (particularly if it failed), so I wrote this script and ran the following:
>my_long_job ; tweet "The job finished with status $? at `date`."

This is instructive to budding linux users:
  • The semicolon means run the second command (tweet) after the first (my_long_job) finishes.
  • The '$?' is a shell variable that holds the exit status of the last command run.
  • `date` runs the `date' program and puts the output into the string.
  • I put the argument to `tweet' in double quotes because the shell will provide variable expansion in a double-quoted string, but will use a single-quoted string verbatim (I wanted it to actually expand $? and `date` into their values, not pass those characters to my program).
If I end up writing a more complete command-line tweet-er I'll post it here. Also, if someone could let me know of a better way to post code snippets on blogger I'd be grateful, because this is terrible.

~KMarsh

2 comments:

  1. But... what does it do?

    ReplyDelete
  2. The program I wrote simply posts a message to twitter. The command line that I showed runs the first command (that I expect to take longer than I want to sit watching it) and then when it's done posts a message to twitter saying if it succeeded or failed.

    ReplyDelete