<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Musings of an Anonymous Geek</title>
	
	<link>http://www.protocolostomy.com</link>
	<description>Made with only the finest 1's and 0's</description>
	<lastBuildDate>Thu, 05 Nov 2009 02:19:17 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/MusingsOfAnAnonymousGeek" type="application/rss+xml" /><feedburner:emailServiceId>MusingsOfAnAnonymousGeek</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FMusingsOfAnAnonymousGeek" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FMusingsOfAnAnonymousGeek" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/MusingsOfAnAnonymousGeek" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FMusingsOfAnAnonymousGeek" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FMusingsOfAnAnonymousGeek" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FMusingsOfAnAnonymousGeek" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Python, Creating XML, Recursion, and Order</title>
		<link>http://feedproxy.google.com/~r/MusingsOfAnAnonymousGeek/~3/-YLdFVdV1Yc/</link>
		<comments>http://www.protocolostomy.com/2009/11/04/python-creating-xml-recursion-and-order/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 02:05:00 +0000</pubDate>
		<dc:creator>m0j0</dc:creator>
				<category><![CDATA[Hacks]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.protocolostomy.com/?p=644</guid>
		<description><![CDATA[I love being challenged every day. Today I ran across a challenge that has several solutions. However, most of them are hacks, and I never feel like I really solved the problem when I implement a hack. There&#8217;s also that eerie feeling that this hack is going to bite me later.
I have an API I [...]]]></description>
			<content:encoded><![CDATA[<p>I love being challenged every day. Today I ran across a challenge that has several solutions. However, most of them are hacks, and I never feel like I really solved the problem when I implement a hack. There&#8217;s also that eerie feeling that this hack is going to bite me later.</p>
<p>I have an API I need to talk to. It&#8217;s pure XML-over-HTTP (henceforth XHTTP). Actually, the first issue I had was just dealing with XHTTP. All of the APIs I&#8217;ve dealt with in the past were either XMLRPC, SOAP, which have ready-made libraries ready to use, or they used GET parameters and the like, which are pretty simple to deal with. I&#8217;ve never had to actually construct an HTTP request and just POST raw XML.</p>
<p>It&#8217;s as easy as it should be, really. I code in Python, so once you actually have an XML message ready to send, you can use urllib2 to send it in about 2 lines of code.</p>
<p>The more interesting part is putting the request together. I thought I had this beat. I decided to use the xml.dom.minidom module and create my Document object by going through the DOMImplementation object, because it was the only thing I found that allowed me to actually specify a DTD programmatically instead of hackishly tacking on hard-coded text. No big deal.</p>
<p>Now that I had a document, I needed to add elements to it. Some of these XML queries I&#8217;m sending can get too long to write a function that manually creates all the elements, then adds them to the document, then creates the text nodes, then adds them to the proper element&#8230; it&#8217;s amazingly tedious to do. I really wish Python had something like PHP&#8217;s XMLWriter, which lets you create an element and its text in one line of code.</p>
<p>Tedium drives me nuts, so rather than code this all out, I decided to create a dictionary that mirrored the structure of my query, with the data for the text nodes filled in by variables.</p>
<pre class="brush: python;">
query_params = {'super_special_query':
                   {
                      'credentials': {'username': user, 'password': password, 'data_realm': realm},
                      'result_params': {'num_results': setsize, 'order_by': order_by},
                       query_type: query_dict
                    }
                }

def makeDoc():
    impl = getDOMImplementation()
    dt = impl.createDocumentType(&quot;super_special&quot;, None, 'super_special.dtd')
    doc = impl.createDocument(None, &quot;super_special&quot;, dt)
    return doc

def makeQuery(doc, query_params, tag=None):
    &quot;&quot;&quot;
        @doc is an xml.minidom.Document object
        @query_params is a dictionary structure that mirrors the structure of the xml.
        @tag used in recursion to keep track of the node to append things to next time through.

    &quot;&quot;&quot;

    if tag is None:
        root = doc.documentElement
    else:
        root = tag

    for key, value in query_params.iteritems():
        tag = doc.createElement(key)
        root.appendChild(tag)
        if isinstance(value, dict):
            makeQuery(doc, value, tag)
        else:
            root.appendChild(tag)
            tag_txt = doc.createTextNode(value)
            tag.appendChild(tag_txt)

    return doc.toxml()

doc = makeDoc()
qxml = makeQuery(doc, query_params)
</pre>
<p>This is simplistic, really. I don&#8217;t need to deal with attributes in my queries, for example. But it is generic enough that if I need to send different types of queries, all that&#8217;s required is creating another dictionary to represent it, and passing that through the same makeQuery function to create the query.</p>
<p>Initial testing indicated success, but that&#8217;s why you can&#8217;t rely on only simple initial tests. Switching things up immediately exposed a problem: The API server validated my query against a DTD that enforced strict ordering of the elements, and Python dictionaries do not have the same notion of &#8220;order&#8221; that you and I do.</p>
<p>So there&#8217;s the code. If nothing else, it&#8217;s a less-contrived example of what you might actually use recursion for. Tomorrow I have to figure out how to enforce the ordering. One idea is to have a separate list to consult for the ordering of the elements. It requires an extra outer loop to go through the list, get the name of the next tag, then use that value to ask the dictionary for any related values. Seemed like a good way to go, but I had a bit of difficulty figuring out how to make that work at all. Maybe with fresh eyes in the AM it&#8217;ll be more obvious &#8212; that happens a lot, and is always a nice surprise.</p>
<p>Ideas, as always, are hereby solicited!</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fwww.protocolostomy.com%2F2009%2F11%2F04%2Fpython-creating-xml-recursion-and-order%2F';
  addthis_title  = 'Python%2C+Creating+XML%2C+Recursion%2C+and+Order';
  addthis_pub    = 'jonesy';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=-YLdFVdV1Yc:cjN9v3KgW9Q:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=-YLdFVdV1Yc:cjN9v3KgW9Q:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=bcOpcFrp8Mo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=-YLdFVdV1Yc:cjN9v3KgW9Q:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?i=-YLdFVdV1Yc:cjN9v3KgW9Q:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/MusingsOfAnAnonymousGeek/~4/-YLdFVdV1Yc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.protocolostomy.com/2009/11/04/python-creating-xml-recursion-and-order/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.protocolostomy.com/2009/11/04/python-creating-xml-recursion-and-order/</feedburner:origLink></item>
		<item>
		<title>It’s so much easier now</title>
		<link>http://feedproxy.google.com/~r/MusingsOfAnAnonymousGeek/~3/W7xFxsalb5s/</link>
		<comments>http://www.protocolostomy.com/2009/11/01/its-so-much-easier-now/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 20:32:58 +0000</pubDate>
		<dc:creator>m0j0</dc:creator>
				<category><![CDATA[Me stuff]]></category>

		<guid isPermaLink="false">http://www.protocolostomy.com/?p=642</guid>
		<description><![CDATA[The information superhighway&#8217;s construction has benefited me in ways I&#8217;ve only been made conscious of this weekend.
I&#8217;ve had a lot of time to myself this weekend, and decided to spend a few solid 1-hour blocks playing guitar. Oh, I still play around the house here and there, but usually if I can get in 20 [...]]]></description>
			<content:encoded><![CDATA[<p>The information superhighway&#8217;s construction has benefited me in ways I&#8217;ve only been made conscious of this weekend.</p>
<p>I&#8217;ve had a lot of time to myself this weekend, and decided to spend a few solid 1-hour blocks playing guitar. Oh, I still play around the house here and there, but usually if I can get in 20 minutes I feel privileged. Learning more kids songs is helping <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>But this weekend I wanted to learn a couple of songs in particular. I wanted to learn &#8220;Why Georgia&#8221; and &#8220;My Stupid Mouth&#8221; from John Mayer&#8217;s &#8220;Room for Squares&#8221; album. Although since that album&#8217;s release Mr. Mayer has gone on to do more produced and (to a guitarist) less interesting things on his commercial albums, Room for Squares contained really wonderful textures and sounds while somehow keeping the guitar front-and-center.</p>
<p>John also uses a lot of cool chords and fingerpicking techniques that I knew I&#8217;d have fun with if I ever had the time to sit down with the songs and my guitar at the same time. I&#8217;ve been playing for almost 25 years, and knew a lot of the chords and techniques, but it&#8217;d be great to be able to use them in songs that people under 30 recognize rather than having to explain (for example) who James Taylor is.</p>
<h3>How I Learn Songs: First Phase</h3>
<p>I learn songs by first listening to them either with headphones on, or at a relatively high volume, about 20 times. I want to become intimate, at a subconscious level, with every detail of the song. I want to feel the tension build, recognize cues from all of the instruments, and understand how they&#8217;re playing off each other. This is wildly important to a one-man musician, because often I try to embellish the final piece to try to put hints of the entire song into the final piece &#8212; not just the guitar part.</p>
<p>Of course, I *start* with the guitar part, because it&#8217;s a bridge to the rest of the song. I learn it as close to note-for-note as possible (where there are solos, the same goes for the solo. I&#8217;m sick that way).</p>
<p>Once I can play the song through along with the recording and not hear anything going awry, I practice it that way several times. Maybe 10 times.</p>
<p>Then the fun begins.</p>
<h3>Having Fun Learning: Second Phase</h3>
<p>When I was a kid, my mom and her sisters liked to go to flea markets. I was not a big fan of these huge collections of what looked like garage sales, until I came across a group of tables with what must&#8217;ve been 1000 cassette tapes (that was the popular audio medium of the day). When I scanned the collection, I noticed an unusually large collection of Jimi Hendrix tapes. I figured they were compilations, but after picking one up, I realized it was actually a random collection of live and unreleased recordings.</p>
<p>Over the course of months I collected as many of these as I could, because Hendrix was an artist that always sent me running to the guitar. All told I had about 6-8 versions of Red House, a classic 12-bar blues jam. I had 3-4 versions of Foxy Lady, another 3 of Purple Haze, and lots more. Going through and picking out differences between the live and recorded versions was a great primer on how you can alter and embellish while staying within the same basic framework of a song without totally destroying it.</p>
<p>From then on, whenever I learned new songs or started studying a particular guitarist, I tried to get as many different versions of different songs as I could, to see how the guitarist thought about the piece. Guitarists on the road forced to play the same songs night after night get bored, and often try to make things interesting by altering different parts of the song, or even by changing the guitar&#8217;s role in different parts of the song. Fascinating stuff.</p>
<h3>Making it Your Own: Third Phase</h3>
<p>I would learn lots of this stuff, again, note-for-note to the best of my ability. I was blessed with a fantastic ear and good sense of rhythm, and that along with practice and constant exercising of those talents made me able to pick out and play even some rather complex stuff in no time. By the time I was 14, I was able to play simple things like Led Zeppelin&#8217;s &#8220;The Lemon Song&#8221; in about an hour (not counting the solo), and most of the stuff on the radio I could begin playing along with accurately before the song was even over.</p>
<p>Even better, there were plenty of &#8220;solo acoustic&#8221; variants of songs, or songs where the live recording happened to pick up the guitar and drums more than the bass and keyboards, or it emphasized the bass and drums more than the guitar. These imperfections are absolute gems for learning more about what&#8217;s going in the song&#8230; or what *could* be going on when you play it!</p>
<p>Once I learn a song and work in some of the original artist&#8217;s own embellishments, some of my own embellishments, and some of my musical personality and influences, it more or less becomes &#8220;my own&#8221;. I can still play a variant faithful to the recording, but it seems boring when you&#8217;ve heard all that can be done with it.</p>
<h3>What&#8217;s Better Now?</h3>
<p>Well, it&#8217;s not like I used to pick a song, spend a weekend with it, and all of a sudden it was my own. While I could easily learn decently solid renditions of songs in a weekend, it would take me months to find different recordings of a particular song, to read magazine articles and sometimes books about guitarists, scouring the words for descriptions of how they played things and thought about them. It would be an ongoing process that sometimes also involved figuring out the players&#8217; influences and tracking down *their* recordings&#8230; ugh.</p>
<p>Today?</p>
<p>*Literally* today, I decided to learn &#8220;Why Georgia&#8221; by John Mayer (I learned a decently solid version of &#8220;My Stupid Mouth&#8221; yesterday). While I was listening to the song in iTunes, I also checked out YouTube and searched for the song there. Boom! 5000 hits. In about an hour, I had heard (AND SEEN!!!) about 10 different performances by John Mayer himself, and I spent about another 20 minutes browsing videos others have posted either covering the song, or providing a tutorial on how to play the song!</p>
<p>Of course, some of the covers and tutorials are horribly wrong, but it&#8217;s easier to pick out stuff that&#8217;s not going to help you on YouTube than it is actually having to play through badly written tablature to figure out it&#8217;s wrong (and the internet, I promise you, is absolutely flooded with bad tablature).</p>
<p>The point is, I was able to learn this song, and work in Mayer&#8217;s embellishments as I went. Watching him play it in live performances, I was able to rely in visual cues and his body language to help me figure out how he thought about the song as he was playing it. Seeing him play in solo acoustic settings vs. live with a whole band was enlightening. In the end, I have learned a version of the piece, in one day, that would probably have taken me months to put together in the 80&#8217;s.</p>
<p>Thanks, Internet!</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fwww.protocolostomy.com%2F2009%2F11%2F01%2Fits-so-much-easier-now%2F';
  addthis_title  = 'It%26%238217%3Bs+so+much+easier+now';
  addthis_pub    = 'jonesy';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=W7xFxsalb5s:_zF9r1T7ras:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=W7xFxsalb5s:_zF9r1T7ras:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=bcOpcFrp8Mo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=W7xFxsalb5s:_zF9r1T7ras:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?i=W7xFxsalb5s:_zF9r1T7ras:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/MusingsOfAnAnonymousGeek/~4/W7xFxsalb5s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.protocolostomy.com/2009/11/01/its-so-much-easier-now/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.protocolostomy.com/2009/11/01/its-so-much-easier-now/</feedburner:origLink></item>
		<item>
		<title>Python Quirks in Cmd, urllib2, and decorators</title>
		<link>http://feedproxy.google.com/~r/MusingsOfAnAnonymousGeek/~3/vDYdG1TCucM/</link>
		<comments>http://www.protocolostomy.com/2009/10/28/python-quirks-in-cmd-urllib2-and-decorators/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 03:06:39 +0000</pubDate>
		<dc:creator>m0j0</dc:creator>
				<category><![CDATA[Hacks]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Sysadmin]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.protocolostomy.com/?p=633</guid>
		<description><![CDATA[So, if you haven&#8217;t been following along, Python programming now occupies the bulk of my work day.
While I really like writing code and like it more using Python, no language is without its quirks. Let me say up front that I don&#8217;t consider these quirks bugs or big hulking issues. I&#8217;m not trying to bash [...]]]></description>
			<content:encoded><![CDATA[<p>So, if you haven&#8217;t been following along, Python programming now occupies the bulk of my work day.</p>
<p>While I really like writing code and like it more using Python, no language is without its quirks. Let me say up front that I don&#8217;t consider these quirks bugs or big hulking issues. I&#8217;m not trying to bash the language. I&#8217;m just trying to help folks who trip over some of these things that I found to be slightly less than obvious.</p>
<h3>Python&#8217;s Cmd Module and Handling Arguments</h3>
<p>Using the Python Cmd module lets you create a program that provides an interactive shell interface to your users. It&#8217;s really simple, too. You just create a class that inherits from cmd.Cmd, and define a bunch of methods named do_&lt;something&gt;, where &lt;something&gt; is the actual command your user will run in your custom shell.</p>
<p>So if you want users to be able to launch your app, be greeted with a prompt, type &#8220;hello&#8221;, and have something happen in response, you just define a method called &#8220;do_hello&#8221; and whatever code you put there will be run when a user types &#8220;hello&#8221; in your shell. Here&#8217;s what that would look like:</p>
<pre class="brush: python;">
import cmd

class MyShell(cmd.Cmd):
   def do_hello(self):
      print &quot;Hello!&quot;

# Kick off the shell
shell = MyShell()
shell.cmdloop()
</pre>
<p>Of course, what&#8217;s a shell without command line options and arguments? For example, I created a shell-based app using Cmd that allowed users to run a &#8216;connect&#8217; command with arguments for host, port, user, and password. Within the shell, the command would look something like this:</p>
<pre>&gt; connect -h mybox -u jonesy -p mypass</pre>
<p>Note that the &#8220;&gt;&#8221; is the prompt, not part of the command.</p>
<p>The idea here is that you pass the arguments to the option flags, and you can set sane defaults in the application for missing args (for example, I didn&#8217;t provide a port here &#8212; I&#8217;m leaning on a default, but I did provide a host, since the default might be &#8216;localhost&#8217;).</p>
<p>Passing just one, single-word argument with Cmd is dead easy, because all of the command methods receive a string that contains *everything* on the line after the actual command. If you&#8217;re expecting such an argument, just make sure your &#8216;do_something&#8217; method accepts the incoming string. So, to let users see what &#8220;hello&#8221; looks like in Spanish, we can accept &#8220;esp&#8221; as an argument to our command:</p>
<pre class="brush: python;">
class MyShell(cmd.Cmd):
   def do_hello(self, arg):
      print &quot;Hello! %s&quot; % arg
</pre>
<p>The problems come when you want more than one argument, or when you want flags with arguments. For example, in the earlier &#8220;connect&#8221; example, my &#8220;do_connect&#8221; method is still only going to get one big, long string passed to it &#8212; not a list of arguments. So where in a normal program you might do something like:</p>
<pre class="brush: python;">
class MyShell(cmd.Cmd):
   def do_connect(self, host='localhost', port='42', user='guest', password='guest'):
      #...connection code here...
</pre>
<p>In a Cmd method, you&#8217;re just going to define it like we did the do_hello method above: it takes &#8217;self&#8217; and &#8216;args&#8217;, where &#8216;args&#8217; is one long line.</p>
<p>A couple of quick workarounds I&#8217;ve tried:</p>
<p><strong>Parse the line yourself.</strong> I created a method in my Cmd app called &#8216;parseargs&#8217; that just takes the big long line and returns a dictionary. My specific application only takes &#8216;name=value&#8217; arguments, so I do this:</p>
<pre>         d = dict([arg.split('=') for arg in args.split()])
</pre>
<p>And return the dictionary to the calling method. My connect method can then check for keys in the dictionary and set things up. It&#8217;s longer an a little more arduous, but not too bad.</p>
<p><strong>Use optparse. </strong>You can instantiate a parser right inside your do_x methods. If you have a lot of methods that all need to take several flags and args, this could become cumbersome, but for one or two it&#8217;s not so bad. The key to doing this is creating a list from the Big Long Line and passing it to the parse_args() method of your parser object. Here&#8217;s what it looks like:</p>
<pre class="brush: python;">
class MyShell(cmd.Cmd):
   def do_touch(self, line):
      parser = optparse.OptionParser()
      parser.add_option('-f', '--file', dest='fname')
      parser.add_option('-d', '--dir', dest='dir')
      (options,args) = parser.parse_args(line.split())

      print &quot;Directory: %s&quot; % options.dir
      print &quot;File name: %s&quot; % options.fname
</pre>
<p>This method is just an example, so don&#8217;t scratch your head looking for &#8220;import os&#8221; or anything <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>This is probably the more elegant solution, since it doesn&#8217;t require you to restrict your users to passing args in a particular way, and doesn&#8217;t require you to come up with fancy CLI argument parsing algorithms.</p>
<h3>Using urllib2 for Pure XML Over HTTP</h3>
<p>I wrote a web service client this week that does pure XML over HTTP to send queries to a service. I&#8217;ve written things <em>like</em> this before using Python, but it turns out, after looking back at my code, I was always either using XMLRPC, SOAP, or going through some wrapper that hid a lot from me in an effort to make my life easier (like the Google Data API). I&#8217;ve never had to <em>try</em> to send a pure XML payload over the wire to a web server.</p>
<p>I figured urllib2 was going to help me out here, and it did, but not before going through some pain due mainly to an odd pattern in various sources of documentation on the topic. I read docs at python.org, effbot.org, a couple of blogs, and did a Google search, and everything, everywhere, seems to indicate that the urllib2.Request object&#8217;s optional &#8220;data&#8221; argument expects a urlencoded string. From http://docs.python.org/library/urllib2.html?highlight=urllib2.request#urllib2.Request</p>
<blockquote><p><em>data</em> should be a buffer in the standard <em>application/x-www-form-urlencoded</em> format</p></blockquote>
<p>The examples on every site I&#8217;ve found always pass whatever &#8216;data&#8217; is through urllib.urlencode() before adding it to the request. I figured urllib2 was no longer my friend, and almost started looking at implementing an HTTPSClient object. Instead I decided to try just passing my unencoded data. What&#8217;s it gonna do, detect that my data wasn&#8217;t urlencoded? Maybe I&#8217;d learn something.</p>
<p>I learned that all of the documentation fails to account for this particular edge case. Go ahead and pass whatever the heck you want in &#8216;data&#8217;. If it&#8217;s what the server on the other end expects, you&#8217;ll be fine. <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Decorators</h3>
<p>I found myself in dark, dusty corners when I had to decide how and where inside of a much larger piece of code to implement a feature. I really wanted to use a decorator, and still think that&#8217;s what I&#8217;ll wind up doing, but then how to implement the decorator isn&#8217;t as straightforward as I&#8217;d like either.</p>
<p>Decorators are used to alter how a decorated function operates. They&#8217;re amazingly useful, because instead of implementing some bit of code in a bunch of methods that themselves live inside a bunch of classes across various modules, or creating an entire class or mixin to inherit from when you only need the code overhead in a couple of edge cases, you can just create a decorator and apply it only to the proper methods or functions.</p>
<p>The lesson I learned is to try very hard to make one solid decision about how your decorator will work up front. Will it be a class? That&#8217;s done somewhat differently than doing it with a function. Will the decorator take arguments? That&#8217;s handled differently in both implementations, and also requires changes to an existing decorator class that didn&#8217;t used to take arguments. I don&#8217;t know why I expected this to be more straightforward, but I totally did.</p>
<p>If you&#8217;re new to decorators or haven&#8217;t had to dig into them too deeply, I highly recommend Bruce Eckel&#8217;s series introducing Python decorators, which walks you through all of the various ways to implement them. Part I (of 3) is <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808">here</a>.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fwww.protocolostomy.com%2F2009%2F10%2F28%2Fpython-quirks-in-cmd-urllib2-and-decorators%2F';
  addthis_title  = 'Python+Quirks+in+Cmd%2C+urllib2%2C+and+decorators';
  addthis_pub    = 'jonesy';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=vDYdG1TCucM:odQujQsa5Us:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=vDYdG1TCucM:odQujQsa5Us:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=bcOpcFrp8Mo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=vDYdG1TCucM:odQujQsa5Us:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?i=vDYdG1TCucM:odQujQsa5Us:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/MusingsOfAnAnonymousGeek/~4/vDYdG1TCucM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.protocolostomy.com/2009/10/28/python-quirks-in-cmd-urllib2-and-decorators/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.protocolostomy.com/2009/10/28/python-quirks-in-cmd-urllib2-and-decorators/</feedburner:origLink></item>
		<item>
		<title>New Job, Car, Baby, and Other News</title>
		<link>http://feedproxy.google.com/~r/MusingsOfAnAnonymousGeek/~3/mzeVb3EkxtE/</link>
		<comments>http://www.protocolostomy.com/2009/10/22/new-job-car-baby-and-other-news/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 02:02:48 +0000</pubDate>
		<dc:creator>m0j0</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[LinuxLaboratory]]></category>
		<category><![CDATA[Other Cool Blogs]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Sysadmin]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.protocolostomy.com/?p=631</guid>
		<description><![CDATA[New Baby!
I know this is my geek blog, but geeks have kids too, so first I want to announce the birth of our second daughter, Sadie, who was born on September 15th. She&#8217;s now over a month old. This is the first time I&#8217;ve stayed up late enough to blog about her. Everyone is healthy, [...]]]></description>
			<content:encoded><![CDATA[<h3>New Baby!</h3>
<p>I know this is my geek blog, but geeks have kids too, so first I want to announce the birth of our second daughter, Sadie, who was born on September 15th. She&#8217;s now over a month old. This is the first time I&#8217;ve stayed up late enough to blog about her. Everyone is healthy, if slightly sleep-deprived <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>New Job!</h3>
<p>The day before Sadie&#8217;s birth, I got a call with an offer for a job. A *full-time* job, as a Senior Operations Developer for <a href="http://myyearbook.com">MyYearbook.com</a>. After learning about the cool and very geeky things going on at MyYearbook during the interview process, I couldn&#8217;t turn it down. I started on October 5, and it&#8217;s been a blast digging into all of the cool stuff going on there. While I&#8217;m certainly doing my fair share of PHP code review, maintenance, and general coding, I&#8217;m also getting plenty of hours in working out the Python side of my brain. I&#8217;m finding that while it&#8217;s easier switching gears than I had anticipated, I do make some really funny minor syntax errors, like using dot notation to access object attributes in PHP ;-P</p>
<p>What I find super exciting is something that might turn some peoples&#8217; stomachs: at the end of my first week, I sat back and looked at my monitors to find roughly 15 tabs in Firefox open to pages explaining various tools I&#8217;d never gotten to use, protocols I&#8217;ve never heard of, etc. I had my laptop and desktop both configured with 2 virtual machines for testing and playing with new stuff. I had something north of 25 terminal windows open, and 8 files open in Komodo Edit.</p>
<p>Now THAT, THAT is FUN!</p>
<p>The projects I&#8217;m working on run the gamut from code cleanups that nobody else has had time to do (a good tool for getting my brain wrapped around various parts of the code base), to working on scalability solutions and new offerings involving my background in coding *and* system administration. It&#8217;s like someone cherry-picked a Bay Area startup and dropped it randomly 30 minutes from my house.</p>
<p>My own business is officially &#8220;not taking new clients&#8221;. I have some regular clients that I still do work for, so my &#8220;regulars&#8221; are still being served, but they&#8217;ve all been put on notice that I&#8217;m unavailable until the new year.</p>
<h3>New Car!</h3>
<p>I&#8217;m less excited about the new car, really. I used to drive a Jeep Liberty, and I loved it. However, in early September, before Sadie&#8217;s arrival, it became clear to me that putting two car seats in that beast wasn&#8217;t going to happen. The Jeep is great for drivers, and it has some cargo space. It&#8217;s not a great vehicle for passengers, though.</p>
<p>At the same time, I was running a business (this was before the job offer came along), and I was finding myself slightly uncomfortable delivering rather serious business proposals in a well-used 2003 Jeep. So, I needed something that could fit my young family (my oldest is 2 yrs), and that was presentable to clients. So, I got a Lexus ES350.</p>
<p>I like most things about the car, except for the audio system. It seems schizophrenic to me to have like 6 sound &#8216;zones&#8217; to isolate the audio to certain sets of speakers, but then controls like bass and treble only go from 0 to 5. Huh? And the sound always sounds like it&#8217;s lying on the floor for some reason. It&#8217;s not at all immersive. The sound system on my Jeep completely kicked ass. I miss it. A lot.</p>
<h3>Other News</h3>
<p>I&#8217;ve submitted an article to <a href="http://pythonmagazine.com">Python Magazine</a> about my (relatively) recent work with Django and my (temporarily stalled) overhaul of <a href="http://linuxlaboratory.org">LinuxLaboratory.org</a>, and my experiences with various learning resources related to Django. If you&#8217;re looking to get into Django, it&#8217;s probably a good read.</p>
<p>I&#8217;ve been getting into some areas of Python that were previously dark, dusty corners, so hopefully I&#8217;ll be writing more about Python here, because writing about something helps me to solidify things in my own brain. Short of that, it serves as a future reference point in case it didn&#8217;t get solidified enough <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>My sister launched<a href="http://thedancejones.com/blog"> The Dance Jones</a>, a blog where she talks about fitness, balance, dance, and stuff I should probably pay much more attention to (I&#8217;m close to declaring war on my gut). Also, if you ever wanted to know how to <a href="http://thedancejones.com/blog/2009/10/19/how-to-shoulder-shimmy/">shoulder shimmy</a> (and who hasn&#8217;t wanted to do that?), you should check it out <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fwww.protocolostomy.com%2F2009%2F10%2F22%2Fnew-job-car-baby-and-other-news%2F';
  addthis_title  = 'New+Job%2C+Car%2C+Baby%2C+and+Other+News';
  addthis_pub    = 'jonesy';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=mzeVb3EkxtE:ifLDZtWoAS4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=mzeVb3EkxtE:ifLDZtWoAS4:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=bcOpcFrp8Mo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=mzeVb3EkxtE:ifLDZtWoAS4:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?i=mzeVb3EkxtE:ifLDZtWoAS4:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/MusingsOfAnAnonymousGeek/~4/mzeVb3EkxtE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.protocolostomy.com/2009/10/22/new-job-car-baby-and-other-news/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.protocolostomy.com/2009/10/22/new-job-car-baby-and-other-news/</feedburner:origLink></item>
		<item>
		<title>Sys/DB Admin and Coder Seeks Others To Build Web “A-Team”</title>
		<link>http://feedproxy.google.com/~r/MusingsOfAnAnonymousGeek/~3/AUJvD1Y1ns4/</link>
		<comments>http://www.protocolostomy.com/2009/09/09/sysdb-admin-and-coder-seeks-others-to-build-web-a-team/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 15:20:22 +0000</pubDate>
		<dc:creator>m0j0</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Freelancing]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Sysadmin]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.protocolostomy.com/?p=627</guid>
		<description><![CDATA[UPDATE: There&#8217;s no location requirement. I kind of assume that I&#8217;m not going to find the best people by geographically limiting my search for potential partners.  
Me: Live in Princeton, NJ area. Over 10 years experience with UNIX/Linux administration, databases and data modeling, and PHP/Perl. About 3 years experience using Python for back-end scripting [...]]]></description>
			<content:encoded><![CDATA[<p>UPDATE: There&#8217;s no location requirement. I kind of assume that I&#8217;m not going to find the best people by geographically limiting my search for potential partners. <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Me: Live in Princeton, NJ area. Over 10 years experience with UNIX/Linux administration, databases and data modeling, and PHP/Perl. About 3 years experience using Python for back-end scripting and system automation, and less than a year of Django experience. Former Director of Technology for AddThis.com (it was bought out), Infrastructure Architect at cs.princeton.edu, and systems consultant/trainer. Creator of Python Magazine, former Editor in Chief of both php|architect *and* Python Magazine, and co-author of &#8220;Linux Server Hacks, volume 2&#8243; (O&#8217;Reilly).</p>
<p>You are one of these:</p>
<ul>
<li>Web graphic designer who has worked on several web-based projects for clients in various industries, understands current best practices and standards, has the tools and experience necessary to create custom graphics, and has some familiarity (secondarily) with PHP and/or Python, Javascript and Ajax. If you regularly make use of table-based web designs or ActiveX controls, this isn&#8217;t you.</li>
<li>Hardcore web developer with at least 6 years experience doing nothing but web-based projects using Javascript and (at some point) *both* PHP and Python, and has worked with or has an interest in Django, Cake, and other frameworks, and understands that client needs often don&#8217;t coincide with the religion of fanboyism. Knowledge of Javascript, Ajax, web standards and security is essential here. If your last &#8220;big project&#8221; was volunteer work to build a website for your kid&#8217;s soccer team, this isn&#8217;t you.</li>
<li>A generalist webmaster (sysadmin/db admin/scripter) with at least 6 years experience working in production *nix environments with good familiarity in the areas of high availability, web servers (specifically Apache), proxy servers and monitoring, and has worked with/supported users like the ones mentioned above on web-based projects. If you have to look at the documentation to figure out how to implement a 301 redirect, this probably isn&#8217;t you.</li>
</ul>
<p>Experience working on a team in larger projects with multiple people would be good. Note that I&#8217;m looking for people to partner with on projects, I&#8217;m not hiring full time employees. Future partnership in a proper business is certainly a possibility, but&#8230; baby steps! I do have a couple of domains that would be great for use with this kind of project if it ever progresses that far <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>I know that other people are out there looking for people to partner with on projects, but there doesn&#8217;t appear to be a common place for them to interact. Maybe that can be a project we undertake together <img src='http://www.protocolostomy.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   &#8212; if there *is* a place where people meet up for this kind of thing, let me know!</p>
<p>Let&#8217;s have fun, and take over the world! Shoot me an email at &#8220;bkjones&#8221; @ Google&#8217;s mail domain.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fwww.protocolostomy.com%2F2009%2F09%2F09%2Fsysdb-admin-and-coder-seeks-others-to-build-web-a-team%2F';
  addthis_title  = 'Sys%2FDB+Admin+and+Coder+Seeks+Others+To+Build+Web+%26%238220%3BA-Team%26%238221%3B';
  addthis_pub    = 'jonesy';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=AUJvD1Y1ns4:rJh1ASnPlNo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=AUJvD1Y1ns4:rJh1ASnPlNo:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?d=bcOpcFrp8Mo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?a=AUJvD1Y1ns4:rJh1ASnPlNo:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/MusingsOfAnAnonymousGeek?i=AUJvD1Y1ns4:rJh1ASnPlNo:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/MusingsOfAnAnonymousGeek/~4/AUJvD1Y1ns4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.protocolostomy.com/2009/09/09/sysdb-admin-and-coder-seeks-others-to-build-web-a-team/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.protocolostomy.com/2009/09/09/sysdb-admin-and-coder-seeks-others-to-build-web-a-team/</feedburner:origLink></item>
	</channel>
</rss>
