parsing command line options kinda like GET variables in Python

I think – OK I know – I had a drink too many last night.

… and tomorrow I'll be working from home to clean up this script that we'll be using to harvest metadata feeds. Currently, just OAI/Simple Dublin Core but the script should support any XML feed as long as it's parse-able via XSLT 1.0 and as long as the paging of items can be facilitated via being in the XML itself (i.e. OAI's brilliant Resumption Token) or via numeric GET variable values a la:

&page=1 ... &p=3 ... &nextPage=4 ... etc.

Anyway, I need a simple way to pass arguments via the command line and for whatever reason I don't want to use the deprecated "optparse" module (well, I guess the reason is it's deprecated) or the "argparse" module.

I think I'll just use the following which lets me pass arguments kinda like GET variables in a URL. Sure, there's no error checking or messaging, but I really don't care. Maybe I'll care more tomorrow when my head's a little clearer.


def args2dict():
  import sys
  args = sys.argv
  args = args[1].split("$")
  args_dict = {}
  for arg in args:
    keyVal = arg.split("=")
    key = keyVal[0]
    val = keyVal[1]
    args_dict[key] = val
  return args_dict
# this returns a dictionary with each variable name as a key; the variable's value is the key's value

Say this is in a script called "" which calls the function a la:

myArgs = args2dict()
print myArgs
print myArgs["a"]
if myArgs.has_key("foo"):
  print "yes"

If I run the following:

$ a=1$b=2$c=3$foo=bar

I get this:

{'a': '1', 'c': '3', 'b': '2', 'foo': 'bar'}


Related Content:

Leave a Comment

Your email address will not be published. Required fields are marked *