Index: b/cloud-init-cfg.py
===================================================================
--- a/cloud-init-cfg.py	2012-06-29 16:29:10.329682066 +0200
+++ b/cloud-init-cfg.py	2012-06-29 16:29:21.841739158 +0200
@@ -43,13 +43,13 @@
     else:
         freq = None
         run_args = []
-        name=sys.argv[1]
+        name = sys.argv[1]
         if len(sys.argv) > 2:
             freq = sys.argv[2]
             if freq == "None":
                 freq = None
         if len(sys.argv) > 3:
-            run_args=sys.argv[3:]
+            run_args = sys.argv[3:]
 
     cloudinit.logging_set_from_cfg_file()
     log = logging.getLogger()
@@ -70,14 +70,14 @@
         #       array[2:] = arguemnts
         if "cloud_config_modules" in cc.cfg:
             for item in cc.cfg["cloud_config_modules"]:
-                if isinstance(item,str):
+                if isinstance(item, str):
                     module_list.append((item,))
-                elif isinstance(item,list):
+                elif isinstance(item, list):
                     module_list.append(item)
                 else:
-                    fail("Failed to parse cloud_config_modules",log)
+                    fail("Failed to parse cloud_config_modules", log)
         else:
-            fail("No cloud_config_modules found in config",log)
+            fail("No cloud_config_modules found in config", log)
     else:
         module_list.append( [ name, freq ] + run_args )
 
@@ -94,22 +94,22 @@
         try:
             log.debug("handling %s with freq=%s and args=%s" %
                 (name, freq, run_args ))
-            cc.handle(name, run_args, freq=freq)
+            cc.handle(name, run_args, freq = freq)
         except:
             log.warn(traceback.format_exc())
             err("config handling of %s, %s, %s failed\n" %
-                (name,freq,run_args), log)
+                (name, freq, run_args), log)
             failures.append(name)
 
     sys.exit(len(failures))
 
-def err(msg,log=None):
+def err(msg, log = None):
     if log:
         log.error(msg)
     sys.stderr.write(msg + "\n")
 
-def fail(msg,log=None):
-    err(msg,log)
+def fail(msg, log = None):
+    err(msg, log)
     sys.exit(1)
 
 if __name__ == '__main__':
Index: b/cloud-init-run-module.py
===================================================================
--- a/cloud-init-run-module.py	2012-06-29 16:29:21.833739112 +0200
+++ b/cloud-init-run-module.py	2012-06-29 16:29:21.841739158 +0200
@@ -20,6 +20,7 @@
 import sys
 import cloudinit
 import logging
+import traceback
 
 def Usage(out = sys.stdout):
     out.write("Usage: cloud-init-run-module freq sem-name mod-name [args]\n")
@@ -31,8 +32,8 @@
         Usage(sys.stderr)
         sys.exit(1)
 
-    (freq,semname,modname)=sys.argv[1:4]
-    run_args=sys.argv[4:]
+    (freq, semname, modname) = sys.argv[1:4]
+    run_args = sys.argv[4:]
 
     cloudinit.logging_set_from_cfg_file()
     log = logging.getLogger()
@@ -41,17 +42,17 @@
     try:
         cloud.get_data_source()
     except Exception, e:
-        fail("Failed to get instance data\n\t%s" % traceback.format_exc(),log)
+        fail("Failed to get instance data\n\t%s" % traceback.format_exc(), log)
 
-    if cloud.sem_has_run(semname,freq):
-        msg="%s already ran %s" % (semname,freq)
+    if cloud.sem_has_run(semname, freq):
+        msg = "%s already ran %s" % (semname, freq)
         sys.stderr.write("%s\n" % msg)
         log.debug(msg)
         sys.exit(0)
 
     try:
         mod = __import__('cloudinit.' + modname)
-        inst = getattr(mod,modname)
+        inst = getattr(mod, modname)
     except:
         fail("Failed to load module cloudinit.%s\n" % modname)
 
@@ -63,19 +64,20 @@
         cfg_path = os.environ[cfg_env_name]
 
     try:
-        cloud.sem_and_run(semname, freq, inst.run, [run_args,cfg_path,log], False)
+        cloud.sem_and_run(semname, freq, inst.run, [ run_args, cfg_path, log ],
+                          False)
     except Exception, e:
-        fail("Execution of %s failed:%s" % (semname,e), log)
+        fail("Execution of %s failed:%s" % (semname, e), log)
 
     sys.exit(0)
 
-def err(msg,log=None):
+def err(msg, log = None):
     if log:
         log.error(msg)
     sys.stderr.write(msg + "\n")
 
-def fail(msg,log=None):
-    err(msg,log)
+def fail(msg, log = None):
+    err(msg, log)
     sys.exit(1)
 
 if __name__ == '__main__':
Index: b/cloud-init.py
===================================================================
--- a/cloud-init.py	2012-06-29 16:29:21.833739112 +0200
+++ b/cloud-init.py	2012-06-29 16:29:21.841739158 +0200
@@ -26,8 +26,8 @@
 import logging
 import errno
 
-def warn(str):
-    sys.stderr.write(str)
+def warn(lstr):
+    sys.stderr.write(lstr)
 
 def main():
     cmds = ( "start", "start-local" )
@@ -41,12 +41,12 @@
 
     now = time.strftime("%a, %d %b %Y %H:%M:%S %z")
     try:
-       uptimef=open("/proc/uptime")
-       uptime=uptimef.read().split(" ")[0]
-       uptimef.close()
-    except IOError, e:
-       warn("unable to open /proc/uptime\n")
-       uptime = "na"
+        uptimef = open("/proc/uptime")
+        uptime = uptimef.read().split(" ")[0]
+        uptimef.close()
+    except IOError:
+        warn("unable to open /proc/uptime\n")
+        uptime = "na"
 
     msg = "cloud-init %s running: %s. up %s seconds" % (cmd, now, uptime)
     sys.stderr.write(msg + "\n")
@@ -66,11 +66,11 @@
     if cmd == "start-local":
         cloudinit.purge_cache()
 
-    cloud = cloudinit.CloudInit(source_type=source_type)
+    cloud = cloudinit.CloudInit(source_type = source_type)
 
     try:
         cloud.get_data_source()
-    except cloudinit.DataSourceNotFoundException, e:
+    except cloudinit.DataSourceNotFoundException:
         sys.stderr.write("no instance data found in %s\n" % cmd)
         sys.exit(1)
 
@@ -84,13 +84,13 @@
     # parse the user data (ec2-run-userdata.py)
     try:
         cloud.sem_and_run("consume_userdata", "once-per-instance",
-            cloud.consume_userdata,[],False)
+            cloud.consume_userdata, [], False)
     except:
         warn("consuming user data failed!\n")
         raise
 
     try:
-        if util.get_cfg_option_bool(cloud.cfg,"preserve_hostname",False):
+        if util.get_cfg_option_bool(cloud.cfg, "preserve_hostname", False):
             log.debug("preserve_hostname is set. not managing hostname")
         else:
             hostname = cloud.get_hostname()
@@ -106,7 +106,7 @@
     # set the defaults (like what ec2-set-defaults.py did)
     try:
         cloud.sem_and_run("set_defaults", "once-per-instance",
-            set_defaults,[ cloud ],False)
+            set_defaults, [ cloud ], False)
     except:
         warn("failed to set defaults\n")
 
@@ -128,9 +128,9 @@
 # read hostname from a 'hostname' file
 # allow for comments and stripping line endings.
 # if file doesn't exist, or no contents, return default
-def read_hostname(filename, default=None):
+def read_hostname(filename, default = None):
     try:
-        fp = open(filename,"r")
+        fp = open(filename, "r")
         lines = fp.readlines()
         fp.close()
         for line in lines:
@@ -141,19 +141,20 @@
             if line:
                 return line
     except IOError, e:
-        if e.errno == errno.ENOENT: pass
+        if e.errno == errno.ENOENT:
+            pass
     return default
     
 def set_hostname(hostname, log):
     try:
         subprocess.Popen(['hostname', hostname]).communicate()
-        util.write_file("/etc/hostname","%s\n" % hostname, 0644)
+        util.write_file("/etc/hostname", "%s\n" % hostname, 0644)
         log.debug("populated /etc/hostname with %s on first boot", hostname)
     except:
         log.error("failed to set_hostname")
 
 def update_hostname(hostname, log):
-    prev_file="%s/%s" % (cloudinit.datadir,"previous-hostname")
+    prev_file = "%s/%s" % (cloudinit.datadir, "previous-hostname")
     etc_file = "/etc/hostname"
 
     hostname_prev = None
@@ -179,14 +180,14 @@
 
     try:
         for fname in update_files:
-            util.write_file(fname,"%s\n" % hostname, 0644)
-            log.debug("wrote %s to %s" % (hostname,fname))
+            util.write_file(fname, "%s\n" % hostname, 0644)
+            log.debug("wrote %s to %s" % (hostname, fname))
     except:
         log.warn("failed to write hostname to %s" % fname)
 
     if hostname_in_etc and hostname_prev and hostname_in_etc != hostname_prev:
         log.debug("%s differs from %s. assuming user maintained" %
-                  (prev_file,etc_file))
+                  (prev_file, etc_file))
 
     if etc_file in update_files:
         log.debug("setting hostname to %s" % hostname)
Index: b/cloudinit/CloudConfig/__init__.py
===================================================================
--- a/cloudinit/CloudConfig/__init__.py	2012-06-29 16:29:21.833739112 +0200
+++ b/cloudinit/CloudConfig/__init__.py	2012-06-29 16:29:21.845739171 +0200
@@ -22,32 +22,34 @@
 import sys
 import traceback
 
-per_instance="once-per-instance"
-per_always="always"
+per_instance = "once-per-instance"
+per_always = "always"
 
 class CloudConfig:
     cfgfile = None
     cfg = None
 
-    def __init__(self,cfgfile):
+    def __init__(self, cfgfile):
         self.cloud = cloudinit.CloudInit()
         self.cfg = self.get_config_obj(cfgfile)
         self.cloud.get_data_source()
 
-    def get_config_obj(self,cfgfile):
+    def get_config_obj(self, cfgfile):
         try:
             cfg = util.read_conf(cfgfile)
         except:
-            cloudinit.log.critical("Failed loading of cloud config '%s'. Continuing with empty config\n" % cfgfile)
+            cloudinit.log.critical("Failed loading of cloud config '%s'. " \
+                                   "Continuing with empty config\n" % cfgfile)
             cloudinit.log.debug(traceback.format_exc() + "\n")
             cfg = None
-        if cfg is None: cfg = { }
-        return(util.mergedict(cfg,self.cloud.cfg))
+        if cfg is None:
+            cfg = { }
+        return(util.mergedict(cfg, self.cloud.cfg))
 
-    def handle(self, name, args, freq=None):
+    def handle(self, name, args, freq = None):
         try:
-            mod = __import__("cc_" + name.replace("-","_"),globals())
-            def_freq = getattr(mod, "frequency",per_instance)
+            mod = __import__("cc_" + name.replace("-", "_"), globals())
+            def_freq = getattr(mod, "frequency", per_instance)
             handler = getattr(mod, "handle")
 
             if not freq:
Index: b/cloudinit/CloudConfig/cc_apt_update_upgrade.py
===================================================================
--- a/cloudinit/CloudConfig/cc_apt_update_upgrade.py	2012-06-29 16:29:10.181681341 +0200
+++ b/cloudinit/CloudConfig/cc_apt_update_upgrade.py	2012-06-29 16:29:21.845739171 +0200
@@ -21,7 +21,7 @@
 import os
 import glob
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, cloud, log, _args):
     update = util.get_cfg_option_bool(cfg, 'apt_update', False)
     upgrade = util.get_cfg_option_bool(cfg, 'apt_upgrade', False)
 
@@ -32,7 +32,7 @@
         else:
             mirror = cloud.get_mirror()
         generate_sources_list(mirror)
-        old_mir = util.get_cfg_option_str(cfg,'apt_old_mirror', \
+        old_mir = util.get_cfg_option_str(cfg, 'apt_old_mirror', \
             "archive.ubuntu.com/ubuntu")
         rename_apt_lists(old_mir, mirror)
 
@@ -53,51 +53,55 @@
 
     pkglist = []
     if 'packages' in cfg:
-        if isinstance(cfg['packages'],list):
+        if isinstance(cfg['packages'], list):
             pkglist = cfg['packages']
-        else: pkglist.append(cfg['packages'])
+        else:
+            pkglist.append(cfg['packages'])
 
     if update or upgrade or pkglist:
         #retcode = subprocess.call(list)
         subprocess.Popen(['apt-get', 'update']).communicate()
 
-    e=os.environ.copy()
-    e['DEBIAN_FRONTEND']='noninteractive'
+    e = os.environ.copy()
+    e['DEBIAN_FRONTEND'] = 'noninteractive'
 
     if upgrade:
-        cmd=[ 'apt-get', '--option', 'Dpkg::Options::=--force-confold',
-              'upgrade', '--assume-yes' ]
+        cmd = [ 'apt-get', '--option', 'Dpkg::Options::=--force-confold',
+                'upgrade', '--assume-yes' ]
 
-        subprocess.Popen(cmd, env=e).communicate()
+        subprocess.Popen(cmd, env = e).communicate()
 
     if pkglist:
-        cmd=['apt-get', 'install', '--assume-yes']
+        cmd = ['apt-get', 'install', '--assume-yes']
         cmd.extend(pkglist)
-        subprocess.Popen(cmd, env=e).communicate()
+        subprocess.Popen(cmd, env = e).communicate()
 
     return(True)
 
 def mirror2lists_fileprefix(mirror):
-    file=mirror
+    lfile = mirror
     # take of http:// or ftp://
-    if file.endswith("/"): file=file[0:-1]
-    pos=file.find("://")
+    if lfile.endswith("/"):
+        lfile = lfile[0:-1]
+    pos = lfile.find("://")
     if pos >= 0:
-        file=file[pos+3:]
-    file=file.replace("/","_")
-    return file
+        lfile = lfile[pos+3:]
+    lfile = lfile.replace("/", "_")
+    return lfile
 
-def rename_apt_lists(omirror,new_mirror,lists_d="/var/lib/apt/lists"):
+def rename_apt_lists(omirror, new_mirror, lists_d = "/var/lib/apt/lists"):
     
-    oprefix="%s/%s" % (lists_d,mirror2lists_fileprefix(omirror))
-    nprefix="%s/%s" % (lists_d,mirror2lists_fileprefix(new_mirror))
-    if(oprefix==nprefix): return
-    olen=len(oprefix)
-    for file in glob.glob("%s_*" % oprefix):
-        os.rename(file,"%s%s" % (nprefix, file[olen:]))
+    oprefix = "%s/%s" % (lists_d, mirror2lists_fileprefix(omirror))
+    nprefix = "%s/%s" % (lists_d, mirror2lists_fileprefix(new_mirror))
+    if(oprefix == nprefix):
+        return
+    olen = len(oprefix)
+    for lfile in glob.glob("%s_*" % oprefix):
+        os.rename(lfile, "%s%s" % (nprefix, lfile[olen:]))
 
 def generate_sources_list(mirror):
-    stdout, stderr = subprocess.Popen(['lsb_release', '-cs'], stdout=subprocess.PIPE).communicate()
+    stdout, _stderr = subprocess.Popen(['lsb_release', '-cs'],
+                                       stdout = subprocess.PIPE).communicate()
     codename = stdout.strip()
 
     util.render_to_file('sources.list', '/etc/apt/sources.list', \
@@ -114,15 +118,16 @@
             elst.append([ "", "missing source" ])
             continue
 
-        source=ent['source']
+        source = ent['source']
         if source.startswith("ppa:"):
-            try: util.subp(["add-apt-repository",source])
+            try:
+                util.subp(["add-apt-repository", source])
             except:
                 elst.append([source, "add-apt-repository failed"])
             continue
 
         if not ent.has_key('filename'):
-            ent['filename']='cloud_config_sources.list'
+            ent['filename'] = 'cloud_config_sources.list'
 
         if not ent['filename'].startswith("/"):
             ent['filename'] = "%s/%s" % \
@@ -130,19 +135,22 @@
 
         if ( ent.has_key('keyid') and not ent.has_key('key') ):
             ks = "keyserver.ubuntu.com"
-            if ent.has_key('keyserver'): ks = ent['keyserver']
+            if ent.has_key('keyserver'):
+                ks = ent['keyserver']
             try:
                 ent['key'] = util.getkeybyid(ent['keyid'], ks)
             except:
-                elst.append([source,"failed to get key from %s" % ks])
+                elst.append([source, "failed to get key from %s" % ks])
                 continue
 
         if ent.has_key('key'):
-            try: util.subp(('apt-key', 'add', '-'), ent['key'])
+            try:
+                util.subp(('apt-key', 'add', '-'), ent['key'])
             except:
                 elst.append([source, "failed add key"])
 
-        try: util.write_file(ent['filename'], source + "\n", omode="ab")
+        try:
+            util.write_file(ent['filename'], source + "\n", omode = "ab")
         except:
             elst.append([source, "failed write to file %s" % ent['filename']])
 
Index: b/cloudinit/CloudConfig/cc_byobu.py
===================================================================
--- a/cloudinit/CloudConfig/cc_byobu.py	2012-06-29 16:29:10.157681217 +0200
+++ b/cloudinit/CloudConfig/cc_byobu.py	2012-06-29 16:29:21.845739171 +0200
@@ -19,19 +19,20 @@
 import subprocess
 import traceback
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
     if len(args) != 0:
         value = args[0]
     else:
-        value = util.get_cfg_option_str(cfg,"byobu_by_default","")
+        value = util.get_cfg_option_str(cfg, "byobu_by_default", "")
 
-    if not value: return
+    if not value:
+        return
 
     if value == "user":
-        user = util.get_cfg_option_str(cfg,"user","ubuntu")
+        user = util.get_cfg_option_str(cfg, "user", "ubuntu")
         cmd = [ 'sudo', '-Hu', user, 'byobu-launcher-install' ]
     elif value == "system":
-        shcmd="echo '%s' | debconf-set-selections && %s" % \
+        shcmd = "echo '%s' | debconf-set-selections && %s" % \
             ( "byobu byobu/launch-by-default boolean true", 
               "dpkg-reconfigure byobu --frontend=noninteractive" )
         cmd = [ "/bin/sh", "-c", shcmd ]
Index: b/cloudinit/CloudConfig/cc_disable_ec2_metadata.py
===================================================================
--- a/cloudinit/CloudConfig/cc_disable_ec2_metadata.py	2012-06-29 16:29:10.145681146 +0200
+++ b/cloudinit/CloudConfig/cc_disable_ec2_metadata.py	2012-06-29 16:29:21.845739171 +0200
@@ -21,7 +21,7 @@
 
 frequency = per_always
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, _cloud, _log, _args):
     if util.get_cfg_option_bool(cfg, "disable_ec2_metadata", False):
-        fwall="route add -host 169.254.169.254 reject"
+        fwall = "route add -host 169.254.169.254 reject"
         subprocess.call(fwall.split(' '))
Index: b/cloudinit/CloudConfig/cc_foo.py
===================================================================
--- a/cloudinit/CloudConfig/cc_foo.py	2012-06-29 16:29:10.169681277 +0200
+++ b/cloudinit/CloudConfig/cc_foo.py	2012-06-29 16:29:21.845739171 +0200
@@ -20,5 +20,5 @@
 from cloudinit.CloudConfig import per_instance
 
 frequency = per_instance
-def handle(name,cfg,cloud,log,args):
-   print "hi"
+def handle(name, cfg, cloud, log, args):
+    print "hi"
Index: b/cloudinit/CloudConfig/cc_grub_dpkg.py
===================================================================
--- a/cloudinit/CloudConfig/cc_grub_dpkg.py	2012-06-29 16:29:10.213681488 +0200
+++ b/cloudinit/CloudConfig/cc_grub_dpkg.py	2012-06-29 16:29:21.845739171 +0200
@@ -16,26 +16,28 @@
 #    You should have received a copy of the GNU General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 import cloudinit.util as util
-import subprocess
 import traceback
 import os
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, _cloud, log, _args):
     
-    idevs=None
-    idevs_empty=None
+    idevs = None
+    idevs_empty = None
 
     if "grub-dpkg" in cfg:
-        idevs=util.get_cfg_option_str(cfg["grub-dpkg"],
-            "grub-pc/install_devices",None)
-        idevs_empty=util.get_cfg_option_str(cfg["grub-dpkg"],
-            "grub-pc/install_devices_empty",None)
+        idevs = util.get_cfg_option_str(cfg["grub-dpkg"],
+            "grub-pc/install_devices", None)
+        idevs_empty = util.get_cfg_option_str(cfg["grub-dpkg"],
+            "grub-pc/install_devices_empty", None)
 
     if os.path.exists("/dev/sda1") and not os.path.exists("/dev/sda"):
-        if idevs == None: idevs=""
-        if idevs_empty == None: idevs_empty="true"
+        if idevs == None:
+            idevs = ""
+        if idevs_empty == None:
+            idevs_empty = "true"
     else:
-        if idevs_empty == None: idevs_empty="false"
+        if idevs_empty == None:
+            idevs_empty = "false"
         if idevs == None:
             idevs = "/dev/sda"
             for dev in ( "/dev/sda", "/dev/vda", "/dev/sda1", "/dev/vda1"):
@@ -49,7 +51,7 @@
     dconf_sel = "grub-pc grub-pc/install_devices string %s\n" % idevs + \
         "grub-pc grub-pc/install_devices_empty boolean %s\n" % idevs_empty
     log.debug("setting grub debconf-set-selections with '%s','%s'" %
-        (idevs,idevs_empty))
+        (idevs, idevs_empty))
 
     try:
         util.subp(('debconf-set-selections'), dconf_sel)
Index: b/cloudinit/CloudConfig/cc_mounts.py
===================================================================
--- a/cloudinit/CloudConfig/cc_mounts.py	2012-06-29 16:29:10.225681544 +0200
+++ b/cloudinit/CloudConfig/cc_mounts.py	2012-06-29 16:29:21.845739171 +0200
@@ -31,9 +31,10 @@
             return True
     return False
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, cloud, log, _args):
     # these are our default set of mounts
-    defmnts = [ [ "ephemeral0", "/mnt", "auto", "defaults,nobootwait", "0", "2" ],
+    defmnts = [ [ "ephemeral0", "/mnt", "auto", "defaults, nobootwait", "0",
+                  "2" ],
                 [ "swap", "none", "swap", "sw", "0", "0" ] ]
 
     # fs_spec, fs_file, fs_vfstype, fs_mntops, fs-freq, fs_passno
@@ -49,7 +50,8 @@
 
     for i in range(len(cfgmnt)):
         # skip something that wasn't a list
-        if not isinstance(cfgmnt[i],list): continue
+        if not isinstance(cfgmnt[i], list):
+            continue
 
         # workaround, allow user to specify 'ephemeral'
         # rather than more ec2 correct 'ephemeral0'
@@ -72,7 +74,7 @@
 
         # in case the user did not quote a field (likely fs-freq, fs_passno)
         for j in range(len(cfgmnt[i])):
-            cfgmnt[i][j]=str(cfgmnt[i][j])
+            cfgmnt[i][j] = str(cfgmnt[i][j])
 
     for i in range(len(cfgmnt)):
         # fill in values with defaults from defvals above
@@ -95,7 +97,8 @@
     # entry has the same device name
     for defmnt in defmnts:
         devname = cloud.device_name_to_device(defmnt[0])
-        if devname is None: continue
+        if devname is None:
+            continue
         if devname.startswith("/"):
             defmnt[0] = devname
         else:
@@ -107,7 +110,8 @@
                 cfgmnt_has = True
                 break
         
-        if cfgmnt_has: continue
+        if cfgmnt_has:
+            continue
         cfgmnt.append(defmnt)
 
 
@@ -115,26 +119,30 @@
     # if the second field is None (not the string, the value) we skip it
     actlist = filter(lambda x: x[1] is not None, cfgmnt)
 
-    if len(actlist) == 0: return
+    if len(actlist) == 0:
+        return
 
-    comment="comment=cloudconfig"
+    comment = "comment=cloudconfig"
     cc_lines = [ ]
     needswap = False
     dirs = [ ]
     for line in actlist:
         # write 'comment' in the fs_mntops, entry,  claiming this
-        line[3]="%s,comment=cloudconfig" % line[3]
-        if line[2] == "swap": needswap = True
-        if line[1].startswith("/"): dirs.append(line[1])
+        line[3] = "%s,comment=cloudconfig" % line[3]
+        if line[2] == "swap":
+            needswap = True
+        if line[1].startswith("/"):
+            dirs.append(line[1])
         cc_lines.append('\t'.join(line))
 
     fstab_lines = [ ]
-    fstab=open("/etc/fstab","r+")
+    fstab = open("/etc/fstab", "r+")
     ws = re.compile("[%s]+" % string.whitespace)
     for line in fstab.read().splitlines():
         try:
             toks = ws.split(line)
-            if toks[3].find(comment) != -1: continue
+            if toks[3].find(comment) != -1:
+                continue
         except:
             pass
         fstab_lines.append(line)
@@ -147,13 +155,20 @@
     fstab.close()
 
     if needswap:
-        try: util.subp(("swapon", "-a"))
-        except: log.warn("Failed to enable swap")
+        try:
+            util.subp(("swapon", "-a"))
+        except:
+            log.warn("Failed to enable swap")
 
     for d in dirs:
-        if os.path.exists(d): continue
-        try: os.makedirs(d)
-        except: log.warn("Failed to make '%s' config-mount\n",d)
+        if os.path.exists(d):
+            continue
+        try:
+            os.makedirs(d)
+        except:
+            log.warn("Failed to make '%s' config-mount\n", d)
 
-    try: util.subp(("mount","-a"))
-    except: log.warn("'mount -a' failed")
+    try:
+        util.subp(("mount", "-a"))
+    except:
+        log.warn("'mount -a' failed")
Index: b/cloudinit/CloudConfig/cc_puppet.py
===================================================================
--- a/cloudinit/CloudConfig/cc_puppet.py	2012-06-29 16:29:10.249681678 +0200
+++ b/cloudinit/CloudConfig/cc_puppet.py	2012-06-29 16:29:21.845739171 +0200
@@ -20,20 +20,25 @@
 import socket
 import subprocess
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, cloud, _log, _args):
     # If there isn't a puppet key in the configuration don't do anything
-    if not cfg.has_key('puppet'): return
+    if not cfg.has_key('puppet'):
+        return
     puppet_cfg = cfg['puppet']
     # Start by installing the puppet package ...
-    e=os.environ.copy()
-    e['DEBIAN_FRONTEND']='noninteractive'
+    e = os.environ.copy()
+    e['DEBIAN_FRONTEND'] = 'noninteractive'
     # Make sure that the apt database is updated since it's not run by
     # default
     # Note: we should have a helper to check if apt-get update 
     # has already been run on this instance to speed the boot time.
-    subprocess.check_call(['apt-get', 'update'], env=e)
-    subprocess.check_call(['apt-get', 'install', '--assume-yes',
-                           'puppet'], env=e)
+    ret = subprocess.call(['apt-get', 'update'], env = e)
+    if ret != 0:
+        raise Exception
+    ret = subprocess.call(['apt-get', 'install', '--assume-yes',
+                           'puppet'], env = e)
+    if ret != 0:
+        raise Exception
     # ... and then update the puppet configuration
     if puppet_cfg.has_key('conf'):
         # Add all sections from the conf object to puppet.conf
@@ -70,9 +75,13 @@
                     puppet_conf_fh.write("%s=\"%s\"\n" % (o, v))
         puppet_conf_fh.close()
     # Set puppet default file to automatically start
-    subprocess.check_call(['sed', '-i',
+    ret = subprocess.call(['sed', '-i',
                            '-e', 's/^START=.*/START=yes/',
                            '/etc/default/puppet'])
+    if ret != 0:
+        raise Exception
     # Start puppetd
-    subprocess.check_call(['service', 'puppet', 'start'])
+    ret = subprocess.call(['service', 'puppet', 'start'])
+    if ret != 0:
+        raise Exception
 
Index: b/cloudinit/CloudConfig/cc_runcmd.py
===================================================================
--- a/cloudinit/CloudConfig/cc_runcmd.py	2012-06-29 16:29:10.201681435 +0200
+++ b/cloudinit/CloudConfig/cc_runcmd.py	2012-06-29 16:29:21.845739171 +0200
@@ -18,25 +18,25 @@
 import cloudinit
 import cloudinit.util as util
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
     if not cfg.has_key("runcmd"):
         return
-    outfile="%s/runcmd" % cloudinit.user_scripts_dir
+    outfile = "%s/runcmd" % cloudinit.user_scripts_dir
 
-    content="#!/bin/sh\n"
-    escaped="%s%s%s%s" % ( "'", '\\', "'", "'" )
+    content = "#!/bin/sh\n"
+    escaped = "%s%s%s%s" % ( "'", '\\', "'", "'" )
     try:
         for args in cfg["runcmd"]:
             # if the item is a list, wrap all items in single tick
             # if its not, then just write it directly
-            if isinstance(args,list):
+            if isinstance(args, list):
                 fixed = [ ]
                 for f in args:
-                    fixed.append("'%s'" % str(f).replace("'",escaped))
-                content="%s%s\n" % ( content, ' '.join(fixed) )
+                    fixed.append("'%s'" % str(f).replace("'", escaped))
+                content = "%s%s\n" % ( content, ' '.join(fixed) )
             else:
-                content="%s%s\n" % ( content, str(args) )
+                content = "%s%s\n" % ( content, str(args) )
 
-        util.write_file(outfile,content,0700)
+        util.write_file(outfile, content, 0700)
     except:
         log.warn("failed to open %s for runcmd" % outfile)
Index: b/cloudinit/CloudConfig/cc_ssh.py
===================================================================
--- a/cloudinit/CloudConfig/cc_ssh.py	2012-06-29 16:29:10.189681364 +0200
+++ b/cloudinit/CloudConfig/cc_ssh.py	2012-06-29 16:29:21.845739171 +0200
@@ -20,11 +20,13 @@
 import glob
 import subprocess
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, cloud, log, _args):
     # remove the static keys from the pristine image
     for f in glob.glob("/etc/ssh/ssh_host_*_key*"):
-        try: os.unlink(f)
-        except: pass
+        try:
+            os.unlink(f)
+        except:
+            pass
 
     if cfg.has_key("ssh_keys"):
         # if there are keys in cloud-config, use them
@@ -35,17 +37,17 @@
             "dsa_public"  : ("/etc/ssh/ssh_host_dsa_key.pub", 0644)
         }
 
-        for key,val in cfg["ssh_keys"].items():
+        for key, val in cfg["ssh_keys"].items():
             if key2file.has_key(key):
-                util.write_file(key2file[key][0],val,key2file[key][1])
+                util.write_file(key2file[key][0], val, key2file[key][1])
     else:
         # if not, generate them
-        genkeys ='ssh-keygen -f /etc/ssh/ssh_host_rsa_key -t rsa -N ""; '
-        genkeys+='ssh-keygen -f /etc/ssh/ssh_host_dsa_key -t dsa -N ""; '
+        genkeys = 'ssh-keygen -f /etc/ssh/ssh_host_rsa_key -t rsa -N ""; '
+        genkeys += 'ssh-keygen -f /etc/ssh/ssh_host_dsa_key -t dsa -N ""; '
         subprocess.call(('sh', '-c', "{ %s } </dev/null" % (genkeys)))
 
     try:
-        user = util.get_cfg_option_str(cfg,'user')
+        user = util.get_cfg_option_str(cfg, 'user')
         disable_root = util.get_cfg_option_bool(cfg, "disable_root", True)
         keys = cloud.get_public_ssh_keys()
 
@@ -53,7 +55,7 @@
             cfgkeys = cfg["ssh_authorized_keys"]
             keys.extend(cfgkeys)
 
-        apply_credentials(keys,user,disable_root)
+        apply_credentials(keys, user, disable_root)
     except:
         log.warn("applying credentials failed!\n")
 
@@ -79,7 +81,8 @@
         setup_user_keys(keys, user, '')
  
     if disable_root:
-        key_prefix = 'command="echo \'Please login as the %s user rather than root user.\';echo;sleep 10" ' % user
+        key_prefix = 'command="echo \'Please login as the %s user rather ' \
+            'than root user.\';echo;sleep 10" ' % user
     else:
         key_prefix = ''
 
Index: b/cloudinit/CloudConfig/cc_ssh_import_id.py
===================================================================
--- a/cloudinit/CloudConfig/cc_ssh_import_id.py	2012-06-29 16:29:10.257681702 +0200
+++ b/cloudinit/CloudConfig/cc_ssh_import_id.py	2012-06-29 16:29:21.845739171 +0200
@@ -19,27 +19,28 @@
 import subprocess
 import traceback
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
     if len(args) != 0:
         user = args[0]
         ids = [ ]
         if len(args) > 1:
             ids = args[1:]
     else:
-        user = util.get_cfg_option_str(cfg,"user","ubuntu")
-        ids = util.get_cfg_option_list_or_str(cfg,"ssh_import_id",[])
+        user = util.get_cfg_option_str(cfg, "user", "ubuntu")
+        ids = util.get_cfg_option_list_or_str(cfg, "ssh_import_id", [])
 
-    if len(ids) == 0: return
+    if len(ids) == 0:
+        return
 
     cmd = [ "sudo", "-Hu", user, "ssh-import-lp-id" ] + ids
 
     log.debug("importing ssh ids. cmd = %s" % cmd)
 
     try:
-        subprocess.check_call(cmd)
-    except subprocess.CalledProcessError as e:
-        log.debug(traceback.format_exc(e))
-        raise Exception("Cmd returned %s: %s" % ( e.returncode, cmd))
-    except OSError as e:
+        retval = subprocess.call(cmd)
+        if retval != 0:
+            log.debug("Cmd returned %s: %s" % (retval, cmd))
+            raise Exception("Cmd returned %s: %s" % (retval, cmd))
+    except OSError, e:
         log.debug(traceback.format_exc(e))
         raise Exception("Cmd failed to execute: %s" % ( cmd ))
Index: b/cloudinit/CloudConfig/cc_updates_check.py
===================================================================
--- a/cloudinit/CloudConfig/cc_updates_check.py	2012-06-29 16:29:10.237681613 +0200
+++ b/cloudinit/CloudConfig/cc_updates_check.py	2012-06-29 16:29:21.845739171 +0200
@@ -22,16 +22,16 @@
 
 cronpre = "/etc/cron.d/cloudinit"
 
-def handle(name,cfg,cloud,log,args):
+def handle(_name, cfg, _cloud, log, _args):
     if not util.get_cfg_option_bool(cfg, 'updates-check', True):
         return
     build_info = "/etc/cloud/build.info"
     if not os.path.isfile(build_info):
         log.warn("no %s file" % build_info)
 
-    avail="%s/%s" % ( cloudinit.datadir, "available.build" )
-    cmd=( "uec-query-builds", "--system-suite", "--config", "%s" % build_info,
-          "--output", "%s" % avail, "is-update-available" )
+    avail = "%s/%s" % ( cloudinit.datadir, "available.build" )
+    cmd = ( "uec-query-builds", "--system-suite", "--config", "%s" % build_info,
+            "--output", "%s" % avail, "is-update-available" )
     try:
         util.subp(cmd)
     except:
@@ -39,9 +39,9 @@
 
     # add a cron entry for this hour and this minute every day
     try:
-        cron=open("%s-%s" % (cronpre, "updates") ,"w")
+        cron = open("%s-%s" % (cronpre, "updates"), "w")
         cron.write("%s root %s\n" % \
-            (time.strftime("%M %H * * *"),' '.join(cmd)))
+            (time.strftime("%M %H * * *"), ' '.join(cmd)))
         cron.close()
     except:
         log.warn("failed to enable cron update system check")
Index: b/cloudinit/DataSource.py
===================================================================
--- a/cloudinit/DataSource.py	2012-06-29 16:29:10.133681109 +0200
+++ b/cloudinit/DataSource.py	2012-06-29 16:29:21.845739171 +0200
@@ -16,8 +16,7 @@
 #    You should have received a copy of the GNU General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-import cloudinit
-import UserDataHandler as ud
+import cloudinit.UserDataHandler as ud
 
 class DataSource:
     userdata = None
@@ -25,7 +24,7 @@
     userdata_raw = None
 
     def __init__(self):
-       pass
+        pass
 
     def get_userdata(self):
         if self.userdata == None:
@@ -37,12 +36,13 @@
 
     def get_public_ssh_keys(self):
         keys = []
-        if not self.metadata.has_key('public-keys'): return([])
-        for keyname, klist in self.metadata['public-keys'].items():
+        if not self.metadata.has_key('public-keys'):
+            return([])
+        for _keyname, klist in self.metadata['public-keys'].items():
             # lp:506332 uec metadata service responds with
             # data that makes boto populate a string for 'klist' rather
             # than a list.
-            if isinstance(klist,str):
+            if isinstance(klist, str):
                 klist = [ klist ]
             for pkey in klist:
                 # there is an empty string at the end of the keylist, trim it
@@ -51,7 +51,7 @@
 
         return(keys)
 
-    def device_name_to_device(self, name):
+    def device_name_to_device(self, _name):
         # translate a 'name' to a device
         # the primary function at this point is on ec2
         # to consult metadata service, that has
@@ -82,5 +82,6 @@
                 r = filter(lambda x: int(x) < 256 and x > 0, toks)
                 if len(r) == 4:
                     return("ip-%s" % '-'.join(r))
-            except: pass
+            except:
+                pass
         return toks[0]
Index: b/cloudinit/DataSourceEc2.py
===================================================================
--- a/cloudinit/DataSourceEc2.py	2012-06-29 16:29:21.833739112 +0200
+++ b/cloudinit/DataSourceEc2.py	2012-06-29 16:29:21.845739171 +0200
@@ -16,17 +16,15 @@
 #    You should have received a copy of the GNU General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-import DataSource
+import cloudinit.DataSource as DataSource
 
 import cloudinit
 import cloudinit.util as util
 import socket
 import urllib2
 import time
-import sys
-import boto_utils
+import cloudinit.boto_utils as boto_utils
 import os.path
-import errno
 
 class DataSourceEc2(DataSource.DataSource):
     api_ver  = '2009-04-04'
@@ -39,14 +37,14 @@
     }
 
     def __init__(self):
-        pass
+        DataSource.DataSource.__init__(self)
 
     def __str__(self):
         return("DataSourceEc2")
 
     def get_data(self):
-        seedret={ }
-        if util.read_optional_seed(seedret,base=self.cachedir + "/"):
+        seedret = { }
+        if util.read_optional_seed(seedret, base = self.cachedir + "/"):
             self.userdata_raw = seedret['user-data']
             self.metadata = seedret['meta-data']
             cloudinit.log.debug("using seeded ec2 data in %s" % self.cachedir)
@@ -84,7 +82,7 @@
             availability_zone = self.get_availability_zone()
 
         try:
-            host="%s.ec2.archive.ubuntu.com" % availability_zone[:-1]
+            host = "%s.ec2.archive.ubuntu.com" % availability_zone[:-1]
             socket.getaddrinfo(host, None, 0, socket.SOCK_STREAM)
             return 'http://%s/ubuntu/' % host
         except:
@@ -96,16 +94,18 @@
         address = '169.254.169.254'
         starttime = time.time()
     
-        url="http://%s/%s/meta-data/instance-id" % (address,self.api_ver)
+        url = "http://%s/%s/meta-data/instance-id" % (address, self.api_ver)
         for x in range(sleeps):
             # given 100 sleeps, this ends up total sleep time of 1050 sec
-            sleeptime=int(x/5)+1
+            sleeptime = int(x/5)+1
 
             reason = ""
             try:
+                socket.setdefaulttimeout(2)
                 req = urllib2.Request(url)
-                resp = urllib2.urlopen(req, timeout=2)
-                if resp.read() != "": return True
+                resp = urllib2.urlopen(req)
+                if resp.read() != "":
+                    return True
                 reason = "empty data [%s]" % resp.getcode()
             except urllib2.HTTPError, e:
                 reason = "http error [%s]" % e.code
@@ -113,7 +113,8 @@
                 reason = "url error [%s]" % e.reason
     
             if x == 0:
-                cloudinit.log.warning("waiting for metadata service at %s\n" % url)
+                cloudinit.log.warning("waiting for metadata service at %s\n" %
+                                      url)
 
             cloudinit.log.warning("  %s [%02s/%s]: %s\n" %
                 (time.strftime("%H:%M:%S"), x+1, sleeps, reason))
@@ -152,16 +153,18 @@
         short = os.path.basename(found)
         
         if not found.startswith("/"):
-            found="/dev/%s" % found
+            found = "/dev/%s" % found
 
         if os.path.exists(found):
             return(found)
 
         for nfrom, tlist in mappings.items():
-            if not short.startswith(nfrom): continue
+            if not short.startswith(nfrom):
+                continue
             for nto in tlist:
                 cand = "/dev/%s%s" % (nto, short[len(nfrom):])
                 if os.path.exists(cand):
-                    cloudinit.log.debug("remapped device name %s => %s" % (found,cand))
+                    cloudinit.log.debug("remapped device name %s => %s" %
+                                        (found, cand))
                     return(cand)
         return ofound
Index: b/cloudinit/DataSourceNoCloud.py
===================================================================
--- a/cloudinit/DataSourceNoCloud.py	2012-06-29 16:29:10.289681865 +0200
+++ b/cloudinit/DataSourceNoCloud.py	2012-06-29 16:29:21.845739171 +0200
@@ -16,14 +16,12 @@
 #    You should have received a copy of the GNU General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-import DataSource
+import cloudinit.DataSource as DataSource
 
 import cloudinit
 import cloudinit.util as util
-import sys
 import os.path
 import os
-import errno
 
 class DataSourceNoCloud(DataSource.DataSource):
     metadata = None
@@ -35,10 +33,10 @@
     seeddir = cloudinit.cachedir + '/nocloud'
 
     def __init__(self):
-        pass
+        DataSource.DataSource.__init__(self)
 
     def __str__(self):
-        mstr="DataSourceNoCloud"
+        mstr = "DataSourceNoCloud"
         mstr = mstr + " [seed=%s]" % self.seed
         return(mstr)
 
@@ -57,13 +55,13 @@
             if parse_cmdline_data(self.cmdline_id, md):
                 found.append("cmdline")
         except:
-            util.logexc(cloudinit.log,util.WARN)
+            util.logexc(cloudinit.log, util.WARN)
             return False
 
         # check to see if the seeddir has data.
-        seedret={ }
-        if util.read_optional_seed(seedret,base=self.seeddir + "/"):
-            md = util.mergedict(md,seedret['meta-data'])
+        seedret = { }
+        if util.read_optional_seed(seedret, base = self.seeddir + "/"):
+            md = util.mergedict(md, seedret['meta-data'])
             ud = seedret['user-data']
             found.append(self.seeddir)
             cloudinit.log.debug("using seeded cache data in %s" % self.seeddir)
@@ -80,7 +78,7 @@
             seedfound = False
             for proto in self.supported_seed_starts:
                 if seedfrom.startswith(proto):
-                    seedfound=proto
+                    seedfound = proto
                     break
             if not seedfound:
                 cloudinit.log.debug("seed from %s not supported by %s" %
@@ -89,14 +87,14 @@
 
             # this could throw errors, but the user told us to do it
             # so if errors are raised, let them raise
-            (md_seed,ud) = util.read_seeded(seedfrom)
+            (md_seed, ud) = util.read_seeded(seedfrom)
             cloudinit.log.debug("using seeded cache data from %s" % seedfrom)
 
             # values in the command line override those from the seed
-            md = util.mergedict(md,md_seed)
+            md = util.mergedict(md, md_seed)
             found.append(seedfrom)
 
-        md = util.mergedict(md,defaults)
+        md = util.mergedict(md, defaults)
         self.seed = ",".join(found)
         self.metadata = md;
         self.userdata_raw = ud
@@ -106,7 +104,7 @@
 # that this module should be used
 # example cmdline:
 #  root=LABEL=uec-rootfs ro ds=nocloud
-def parse_cmdline_data(ds_id,fill,cmdline=None):
+def parse_cmdline_data(ds_id, fill, cmdline = None):
     if cmdline is None:
         if 'DEBUG_PROC_CMDLINE' in os.environ:
             cmdline = os.environ["DEBUG_PROC_CMDLINE"]
@@ -119,30 +117,32 @@
         if not ( " %s " % ds_id in cmdline or " %s;" % ds_id in cmdline ):
             return False
 
-    argline=""
+    argline = ""
     # cmdline can contain:
     # ds=nocloud[;key=val;key=val]
     for tok in cmdline.split():
-        if tok.startswith(ds_id): argline=tok.split("=",1)
+        if tok.startswith(ds_id):
+            argline = tok.split("=", 1)
     
     # argline array is now 'nocloud' followed optionally by
     # a ';' and then key=value pairs also terminated with ';'
-    tmp=argline[1].split(";")
+    tmp = argline[1].split(";")
     if len(tmp) > 1:
-        kvpairs=tmp[1:]
+        kvpairs = tmp[1:]
     else:
-        kvpairs=()
+        kvpairs = ()
 
     # short2long mapping to save cmdline typing
     s2l = {  "h" : "local-hostname", "i" : "instance-id", "s" : "seedfrom" }
     for item in kvpairs:
         try:
-            (k,v) = item.split("=",1)
+            (k, v) = item.split("=", 1)
         except:
-            k=item
-            v=None
-        if k in s2l: k=s2l[k]
-        fill[k]=v
+            k = item
+            v = None
+        if k in s2l:
+            k = s2l[k]
+        fill[k] = v
 
     return(True)
 
Index: b/cloudinit/UserDataHandler.py
===================================================================
--- a/cloudinit/UserDataHandler.py	2012-06-29 16:29:21.833739112 +0200
+++ b/cloudinit/UserDataHandler.py	2012-06-29 16:29:21.845739171 +0200
@@ -17,11 +17,13 @@
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 import email
 
-from email import MIMEMultipart
-from email import MIMEText
+from email.MIMEMultipart import MIMEMultipart
+from email.MIMEText import MIMEText
+from email.MIMEBase import MIMEBase
+from email import Encoders
 
 
-starts_with_mappings={
+starts_with_mappings = {
     '#include' : 'text/x-include-url',
     '#!' : 'text/x-shellscript',
     '#cloud-config' : 'text/cloud-config',
@@ -31,32 +33,34 @@
 }
 
 # if 'str' is compressed return decompressed otherwise return it
-def decomp_str(str):
+def decomp_str(lstr):
     import StringIO
     import gzip
     try:
-        uncomp = gzip.GzipFile(None,"rb",1,StringIO.StringIO(str)).read()
+        uncomp = gzip.GzipFile(None, "rb", 1, StringIO.StringIO(lstr)).read()
         return(uncomp)
     except:
-        return(str)
+        return(lstr)
 
-def do_include(str,parts):
+def do_include(lstr, parts):
     import urllib
     # is just a list of urls, one per line
-    for line in str.splitlines():
-        if line == "#include": continue
-        if line.startswith("#"): continue
+    for line in lstr.splitlines():
+        if line == "#include":
+            continue
+        if line.startswith("#"):
+            continue
         content = urllib.urlopen(line).read()
-        process_includes(email.message_from_string(decomp_str(content)),parts)
+        process_includes(email.message_from_string(decomp_str(content)), parts)
 
-def process_includes(msg,parts):
+def process_includes(msg, parts):
     # parts is a dictionary of arrays
     # parts['content']
     # parts['names']
     # parts['types']
     for t in ( 'content', 'names', 'types' ):
         if not parts.has_key(t):
-            parts[t]=[ ]
+            parts[t] = [ ]
     for part in msg.walk():
         # multipart/* are just containers
         if part.get_content_maintype() == 'multipart':
@@ -67,8 +71,8 @@
         ctype = None
         ctype_orig = part.get_content_type()
         if ctype_orig == "text/plain":
-            for str, gtype in starts_with_mappings.items():
-                if payload.startswith(str):
+            for lstr, gtype in starts_with_mappings.items():
+                if payload.startswith(lstr):
                     ctype = gtype
                     break
 
@@ -76,7 +80,7 @@
             ctype = ctype_orig
 
         if ctype == 'text/x-include-url':
-            do_include(payload,parts)
+            do_include(payload, parts)
             continue
 
         filename = part.get_filename()
@@ -96,34 +100,35 @@
             # No guess could be made, or the file is encoded (compressed), so
             # use a generic bag-of-bits type.
             ctype = 'application/octet-stream'
-        else: ctype = parts['types'][i]
+        else:
+            ctype = parts['types'][i]
         maintype, subtype = ctype.split('/', 1)
         if maintype == 'text':
-            msg = MIMEText(parts['content'][i], _subtype=subtype)
+            msg = MIMEText(parts['content'][i], _subtype = subtype)
         else:
             msg = MIMEBase(maintype, subtype)
             msg.set_payload(parts['content'][i])
             # Encode the payload using Base64
-            encoders.encode_base64(msg)
+            Encoders.encode_base64(msg)
         # Set the filename parameter
         msg.add_header('Content-Disposition', 'attachment', 
-            filename=parts['names'][i])
+            filename = parts['names'][i])
         outer.attach(msg)
 
-        i=i+1
+        i = i+1
     return(outer.as_string())
 
 # this is heavily wasteful, reads through userdata string input
 def preprocess_userdata(data):
     parts = { }
-    process_includes(email.message_from_string(decomp_str(data)),parts)
+    process_includes(email.message_from_string(decomp_str(data)), parts)
     return(parts2mime(parts))
 
 # callbacks is a dictionary with:
 #  { 'content-type': handler(data,content_type,filename,payload) }
-def walk_userdata(str, callbacks, data = None):
+def walk_userdata(lstr, callbacks, data = None):
     partnum = 0
-    for part in email.message_from_string(str).walk():
+    for part in email.message_from_string(lstr).walk():
         # multipart/* are just containers
         if part.get_content_maintype() == 'multipart':
             continue
@@ -137,14 +142,14 @@
             filename = 'part-%03d' % partnum
 
         if callbacks.has_key(ctype):
-            callbacks[ctype](data,ctype,filename,part.get_payload())
+            callbacks[ctype](data, ctype, filename, part.get_payload())
 
         partnum = partnum+1
 
 if __name__ == "__main__":
     import sys
-    data = decomp_str(file(sys.argv[1]).read())
-    parts = { }
-    process_includes(email.message_from_string(data),parts)
-    print "#found %s parts" % len(parts['content'])
-    print parts2mime(parts)
+    gdata = decomp_str(file(sys.argv[1]).read())
+    gparts = { }
+    process_includes(email.message_from_string(gdata), gparts)
+    print "#found %s parts" % len(gparts['content'])
+    print parts2mime(gparts)
Index: b/cloudinit/__init__.py
===================================================================
--- a/cloudinit/__init__.py	2012-06-29 16:29:21.833739112 +0200
+++ b/cloudinit/__init__.py	2012-06-29 16:29:21.845739171 +0200
@@ -90,7 +90,7 @@
 
 """
 
-built_in_log_clougLogHandlerLog="""
+built_in_log_clougLogHandlerLog = """
 [handler_cloudLogHandler]
 class=FileHandler
 level=DEBUG
@@ -98,7 +98,7 @@
 args=('__CLOUDINIT_LOGGER_FILE__',)
 """
 
-built_in_log_cloudLogHandlerSyslog= """
+built_in_log_cloudLogHandlerSyslog = """
 [handler_cloudLogHandler]
 class=handlers.SysLogHandler
 level=DEBUG
@@ -117,38 +117,41 @@
 import pwd
 import subprocess
 import yaml
-import util
+import cloudinit.util as util
 import logging
 import logging.config
 import StringIO
 
 class NullHandler(logging.Handler):
-	def emit(self,record): pass
+    def emit(self, record):
+        pass
 
 log = logging.getLogger(logger_name)
 log.addHandler(NullHandler())
 
-def logging_set_from_cfg_file(cfg_file=system_config):
-    logging_set_from_cfg(util.get_base_cfg(cfg_file,cfg_builtin))
+def logging_set_from_cfg_file(cfg_file = system_config):
+    logging_set_from_cfg(util.get_base_cfg(cfg_file, cfg_builtin))
 
-def logging_set_from_cfg(cfg, logfile=None):
+def logging_set_from_cfg(cfg, logfile = None):
     if logfile is None:
         try:
-            open(def_log_file,"a").close()
+            open(def_log_file, "a").close()
             logfile = def_log_file
         except IOError, e:
             if e.errno == errno.EACCES:
                 logfile = "/dev/null"
-            else: raise
+            else:
+                raise
     
-    logcfg=util.get_cfg_option_str(cfg, "log_cfg", "built_in")
+    logcfg = util.get_cfg_option_str(cfg, "log_cfg", "built_in")
     failsafe = "%s\n%s" % (built_in_log_base, built_in_log_clougLogHandlerLog)
     builtin = False
     if logcfg.lower() == "built_in":
-        logcfg = "%s\n%s" % (built_in_log_base, built_in_log_cloudLogHandlerSyslog)
+        logcfg = "%s\n%s" % (built_in_log_base,
+                             built_in_log_cloudLogHandlerSyslog)
         builtin = True
 
-    logcfg=logcfg.replace("__CLOUDINIT_LOGGER_FILE__",logfile)
+    logcfg = logcfg.replace("__CLOUDINIT_LOGGER_FILE__", logfile)
     try:
         logging.config.fileConfig(StringIO.StringIO(logcfg))
         return
@@ -156,12 +159,12 @@
         if not builtin:
             sys.stderr.write("Warning, setting config.fileConfig failed\n")
 
-    failsafe=failsafe.replace("__CLOUDINIT_LOGGER_FILE__",logfile)
+    failsafe = failsafe.replace("__CLOUDINIT_LOGGER_FILE__", logfile)
     logging.config.fileConfig(StringIO.StringIO(failsafe))
 
-import DataSourceEc2
-import DataSourceNoCloud
-import UserDataHandler
+import cloudinit.DataSourceEc2 as DataSourceEc2
+import cloudinit.DataSourceNoCloud as DataSourceNoCloud
+import cloudinit.UserDataHandler as UserDataHandler
 
 class CloudInit:
     datasource_map = {
@@ -188,23 +191,26 @@
             'text/part-handler' : self.handle_handler,
             'text/cloud-boothook' : self.handle_cloud_boothook
         }
-        self.sysconfig=sysconfig
-        self.cfg=self.read_cfg()
+        self.sysconfig = sysconfig
+        self.cfg = self.read_cfg()
         self.source_type = source_type
+        self.handlercount = 0
+        self.cloud_config_str = ""
+        self.datasource_name = ""
 
     def read_cfg(self):
         if self.cfg:
             return(self.cfg)
 
-        conf = util.get_base_cfg(system_config,cfg_builtin)
+        conf = util.get_base_cfg(system_config, cfg_builtin)
 
         # support reading the old ConfigObj format file and merging
         # it into the yaml dictionary
         try:
-            from configobj import ConfigObj
             oldcfg = ConfigObj(self.old_conffile)
-            if oldcfg is None: oldcfg = { }
-            conf = util.mergedict(conf,oldcfg)
+            if oldcfg is None:
+                oldcfg = { }
+            conf = util.mergedict(conf, oldcfg)
         except:
             pass
 
@@ -212,7 +218,7 @@
 
     def restore_from_cache(self):
         try:
-            f=open(data_source_cache, "rb")
+            f = open(data_source_cache, "rb")
             data = cPickle.load(f)
             self.datasource = data
             return True
@@ -227,9 +233,9 @@
                 return False
                 
         try:
-            f=open(data_source_cache, "wb")
-            data = cPickle.dump(self.datasource,f)
-            os.chmod(data_source_cache,0400)
+            f = open(data_source_cache, "wb")
+            _data = cPickle.dump(self.datasource, f)
+            os.chmod(data_source_cache, 0400)
             return True
         except:
             return False
@@ -238,19 +244,20 @@
         pass
 
     def get_data_source(self):
-        if self.datasource is not None: return True
+        if self.datasource is not None:
+            return True
 
         if self.restore_from_cache():
             log.debug("restored from cache type %s" % self.datasource)
             return True
 
-        dslist=[ ]
-        cfglist=self.cfg['cloud_type']
+        dslist = [ ]
+        cfglist = self.cfg['cloud_type']
         if cfglist == "auto":
             dslist = self.auto_orders[self.source_type]
         elif cfglist:
             for ds in cfglist.split(','):
-                dslist.append(strip(ds).tolower())
+                dslist.append(ds.strip().tolower())
             
         for ds in dslist:
             if ds not in self.datasource_map:
@@ -264,9 +271,8 @@
                     log.debug("found data source %s" % ds)
                     return True
             except Exception, e:
-                log.warn("get_data of %s raised %s" % (ds,e))
+                log.warn("get_data of %s raised %s" % (ds, e))
                 util.logexc(log)
-                pass
         log.debug("did not find data source from %s" % dslist)
         raise DataSourceNotFoundException("Could not find data source")
 
@@ -283,25 +289,26 @@
 
     def initctl_emit(self):
         subprocess.Popen(['initctl', 'emit', 'cloud-config',
-            '%s=%s' % (cfg_env_name,cloud_config)]).communicate()
+            '%s=%s' % (cfg_env_name, cloud_config)]).communicate()
 
-    def sem_getpath(self,name,freq):
+    def sem_getpath(self, name, freq):
         freqtok = freq
         if freq == 'once-per-instance':
             freqtok = self.datasource.get_instance_id()
 
-        return("%s/%s.%s" % (semdir,name,freqtok))
+        return("%s/%s.%s" % (semdir, name, freqtok))
     
-    def sem_has_run(self,name,freq):
-        if freq == "always": return False
-        semfile = self.sem_getpath(name,freq)
+    def sem_has_run(self, name, freq):
+        if freq == "always":
+            return False
+        semfile = self.sem_getpath(name, freq)
         if os.path.exists(semfile):
             return True
         return False
     
-    def sem_acquire(self,name,freq):
+    def sem_acquire(self, name, freq):
         from time import time
-        semfile = self.sem_getpath(name,freq)
+        semfile = self.sem_getpath(name, freq)
     
         try:
             os.makedirs(os.path.dirname(semfile))
@@ -314,15 +321,15 @@
     
         # race condition
         try:
-            f = open(semfile,"w")
+            f = open(semfile, "w")
             f.write("%s\n" % str(time()))
             f.close()
         except:
             return(False)
         return(True)
     
-    def sem_clear(self,name,freq):
-        semfile = self.sem_getpath(name,freq)
+    def sem_clear(self, name, freq):
+        semfile = self.sem_getpath(name, freq)
         try:
             os.unlink(semfile)
         except OSError, e:
@@ -335,49 +342,51 @@
     # if that does not exist, then call 'func' with given 'args'
     # if 'clear_on_fail' is True and func throws an exception
     #  then remove the lock (so it would run again)
-    def sem_and_run(self,semname,freq,func,args=[],clear_on_fail=False):
-        if self.sem_has_run(semname,freq):
+    def sem_and_run(self, semname, freq, func, args = [],
+                    clear_on_fail = False):
+        if self.sem_has_run(semname, freq):
             log.debug("%s already ran %s", semname, freq)
             return
         try:
-            if not self.sem_acquire(semname,freq):
+            if not self.sem_acquire(semname, freq):
                 raise Exception("Failed to acquire lock on %s" % semname)
 
             func(*args)
         except:
             if clear_on_fail:
-                self.sem_clear(semname,freq)
+                self.sem_clear(semname, freq)
             raise
 
     def consume_userdata(self):
         self.get_userdata()
         data = self
         # give callbacks opportunity to initialize
-        for ctype, func in self.part_handlers.items():
-            func(data, "__begin__",None,None)
+        for _ctype, func in self.part_handlers.items():
+            func(data, "__begin__", None, None)
         UserDataHandler.walk_userdata(self.get_userdata(),
             self.part_handlers, data)
 
         # give callbacks opportunity to finalize
-        for ctype, func in self.part_handlers.items():
-            func(data,"__end__",None,None)
+        for _ctype, func in self.part_handlers.items():
+            func(data, "__end__", None, None)
 
-    def handle_handler(self,data,ctype,filename,payload):
-        if ctype == "__end__": return
+    def handle_handler(self, data, ctype, _filename, payload):
+        if ctype == "__end__":
+            return
         if ctype == "__begin__" :
             self.handlercount = 0
             return
 
         # add the path to the plugins dir to the top of our list for import
         if self.handlercount == 0:
-            sys.path.insert(0,pluginsdir)
+            sys.path.insert(0, pluginsdir)
 
-        self.handlercount=self.handlercount+1
+        self.handlercount = self.handlercount+1
 
         # write content to pluginsdir
-        modname  = 'part-handler-%03d' % self.handlercount
+        modname = 'part-handler-%03d' % self.handlercount
         modfname = modname + ".py"
-        util.write_file("%s/%s" % (pluginsdir,modfname), payload, 0600)
+        util.write_file("%s/%s" % (pluginsdir, modfname), payload, 0600)
 
         try:
             mod = __import__(modname)
@@ -385,7 +394,7 @@
             handler = getattr(mod, "handle_part")
         except:
             import traceback
-            traceback.print_exc(file=sys.stderr)
+            traceback.print_exc(file = sys.stderr)
             return
 
         # - call it with '__begin__'
@@ -393,27 +402,29 @@
 
         # - add it self.part_handlers
         for mtype in lister():
-            self.part_handlers[mtype]=handler
+            self.part_handlers[mtype] = handler
 
-    def handle_user_script(self,data,ctype,filename,payload):
-        if ctype == "__end__": return
+    def handle_user_script(self, _data, ctype, filename, payload):
+        if ctype == "__end__":
+            return
         if ctype == "__begin__":
             # maybe delete existing things here
             return
 
-        filename=filename.replace(os.sep,'_')
-        util.write_file("%s/%s" % (user_scripts_dir,filename), payload, 0700)
+        filename = filename.replace(os.sep, '_')
+        util.write_file("%s/%s" % (user_scripts_dir, filename), payload, 0700)
 
-    def handle_upstart_job(self,data,ctype,filename,payload):
-        if ctype == "__end__" or ctype == "__begin__": return
+    def handle_upstart_job(self, _data, ctype, filename, payload):
+        if ctype == "__end__" or ctype == "__begin__":
+            return
         if not filename.endswith(".conf"):
-            filename=filename+".conf"
+            filename = filename+".conf"
 
-        util.write_file("%s/%s" % ("/etc/init",filename), payload, 0644)
+        util.write_file("%s/%s" % ("/etc/init", filename), payload, 0644)
 
-    def handle_cloud_config(self,data,ctype,filename,payload):
+    def handle_cloud_config(self, _data, ctype, filename, payload):
         if ctype == "__begin__":
-            self.cloud_config_str=""
+            self.cloud_config_str = ""
             return
         if ctype == "__end__":
             util.write_file(cloud_config, self.cloud_config_str, 0600)
@@ -428,42 +439,44 @@
 
             return
 
-        self.cloud_config_str+="\n#%s\n%s" % (filename,payload)
+        self.cloud_config_str += "\n#%s\n%s" % (filename, payload)
 
-    def handle_cloud_boothook(self,data,ctype,filename,payload):
-        if ctype == "__end__": return
-        if ctype == "__begin__": return
-
-        filename=filename.replace(os.sep,'_')
-        prefix="#cloud-boothook"
-        dos=False
+    def handle_cloud_boothook(self, _data, ctype, filename, payload):
+        if ctype == "__end__":
+            return
+        if ctype == "__begin__":
+            return
+
+        filename = filename.replace(os.sep, '_')
+        prefix = "#cloud-boothook"
+        dos = False
         start = 0
         if payload.startswith(prefix):
             start = len(prefix)
             if payload[start] == '\r':
-                start=start+1
+                start = start+1
                 dos = True
         else:
-            if payload.find('\r\n',0,100) >= 0:
+            if payload.find('\r\n', 0, 100) >= 0:
                 dos = True
     
         if dos:
-            payload=payload[start:].replace('\r\n','\n')
+            payload = payload[start:].replace('\r\n', '\n')
         elif start != 0:
-            payload=payload[start:]
+            payload = payload[start:]
     
-        filepath = "%s/%s" % (boothooks_dir,filename)
+        filepath = "%s/%s" % (boothooks_dir, filename)
         util.write_file(filepath, payload, 0700)
         try:
-            env=os.environ.copy()
-            env['INSTANCE_ID']= self.datasource.get_instance_id()
-            ret = subprocess.check_call([filepath], env=env)
-        except subprocess.CalledProcessError, e:
-            log.error("boothooks script %s returned %i" %
-                (filepath,e.returncode))
+            env = os.environ.copy()
+            env['INSTANCE_ID'] = self.datasource.get_instance_id()
+            ret = subprocess.call([filepath], env = env)
+            if ret != 0:
+                log.error("boothooks script %s returned %i" %
+                          (filepath, ret))
         except Exception, e:
             log.error("boothooks unknown exception %s when running %s" %
-                (e,filepath))
+                (e, filepath))
 
     def get_public_ssh_keys(self):
         return(self.datasource.get_public_ssh_keys())
@@ -477,7 +490,7 @@
     def get_hostname(self):
         return(self.datasource.get_hostname())
 
-    def device_name_to_device(self,name):
+    def device_name_to_device(self, name):
         return(self.datasource.device_name_to_device(name))
 
 
@@ -485,7 +498,8 @@
     try:
         os.unlink(data_source_cache)
     except OSError, e:
-        if e.errno != errno.ENOENT: return(False)
+        if e.errno != errno.ENOENT:
+            return(False)
     except:
         return(False)
     return(True)
Index: b/cloudinit/boto_utils.py
===================================================================
--- a/cloudinit/boto_utils.py	2012-06-29 16:29:10.281681837 +0200
+++ b/cloudinit/boto_utils.py	2012-06-29 16:29:21.845739171 +0200
@@ -46,7 +46,7 @@
         except urllib2.HTTPError, e:
             # in 2.6 you use getcode(), in 2.5 and earlier you use code
             if hasattr(e, 'getcode'):
-                code = e.getcode()
+                code = e.getcode() # pylint: disable=E1101
             else:
                 code = e.code
             if code == 404 and not retry_on_404:
Index: b/cloudinit/execute.py
===================================================================
--- a/cloudinit/execute.py	2012-06-29 16:29:21.833739112 +0200
+++ b/cloudinit/execute.py	2012-06-29 16:29:21.845739171 +0200
@@ -15,15 +15,14 @@
 #
 #    You should have received a copy of the GNU General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-def run(args,cfg,log):
+def run(args, _cfg, log):
     import subprocess
     import traceback
     try:
-        subprocess.check_call(args)
-        return
-    except subprocess.CalledProcessError, e:
-        log.debug(traceback.format_exc(e))
-        raise Exception("Cmd returned %s: %s" % ( e.returncode, args ))
+        retval = subprocess.call(args)
+        if retval != 0:
+            log.debug("Cmd returned %s: %s" % ( retval, args ))
+            raise Exception("Cmd returned %s: %s" % ( retval, args ))
     except OSError, e:
         log.debug(traceback.format_exc(e))
         raise Exception("Cmd failed to execute: %s" % ( args ))
Index: b/cloudinit/util.py
===================================================================
--- a/cloudinit/util.py	2012-06-29 16:29:21.837739129 +0200
+++ b/cloudinit/util.py	2012-06-29 16:29:21.845739171 +0200
@@ -20,10 +20,10 @@
 import errno
 import subprocess
 from Cheetah.Template import Template
-import cloudinit
 import urllib2
 import logging
 import traceback
+import socket
 
 WARN = logging.WARN
 DEBUG = logging.DEBUG
@@ -31,93 +31,100 @@
 
 def read_conf(fname):
     try:
-	    stream = open(fname,"r")
-	    conf = yaml.load(stream)
-	    stream.close()
-	    return conf
+        stream = open(fname, "r")
+        conf = yaml.load(stream)
+        stream.close()
+        return conf
     except IOError, e:
         if e.errno == errno.ENOENT:
             return { }
         raise
 
-def get_base_cfg(cfgfile,cfg_builtin=""):
+def get_base_cfg(cfgfile, cfg_builtin = ""):
     syscfg = read_conf(cfgfile)
     if cfg_builtin:
         builtin = yaml.load(cfg_builtin)
     else:
         return(syscfg)
-    return(mergedict(syscfg,builtin))
+    return(mergedict(syscfg, builtin))
 
-def get_cfg_option_bool(yobj, key, default=False):
-    if not yobj.has_key(key): return default
+def get_cfg_option_bool(yobj, key, default = False):
+    if not yobj.has_key(key):
+        return default
     val = yobj[key]
-    if val is True: return True
+    if val is True:
+        return True
     if str(val).lower() in [ 'true', '1', 'on', 'yes']:
         return True
     return False
 
-def get_cfg_option_str(yobj, key, default=None):
-    if not yobj.has_key(key): return default
+def get_cfg_option_str(yobj, key, default = None):
+    if not yobj.has_key(key):
+        return default
     return yobj[key]
 
-def get_cfg_option_list_or_str(yobj, key, default=None):
-    if not yobj.has_key(key): return default
-    if isinstance(yobj[key],list): return yobj[key]
+def get_cfg_option_list_or_str(yobj, key, default = None):
+    if not yobj.has_key(key):
+        return default
+    if isinstance(yobj[key], list):
+        return yobj[key]
     return([yobj[key]])
 
 # merge values from src into cand.
 # if src has a key, cand will not override
-def mergedict(src,cand):
-    if isinstance(src,dict) and isinstance(cand,dict):
-        for k,v in cand.iteritems():
+def mergedict(src, cand):
+    if isinstance(src, dict) and isinstance(cand, dict):
+        for k, v in cand.iteritems():
             if k not in src:
                 src[k] = v
             else:
-                src[k] = mergedict(src[k],v)
+                src[k] = mergedict(src[k], v)
     return src
 
-def write_file(file,content,mode=0644,omode="wb"):
-        try:
-            os.makedirs(os.path.dirname(file))
-        except OSError, e:
-            if e.errno != errno.EEXIST:
-                raise e
-
-        f=open(file,omode)
-        if mode != None:
-            os.chmod(file,mode)
-        f.write(content)
-        f.close()
+def write_file(lfile, content, mode = 0644, omode = "wb"):
+    try:
+        os.makedirs(os.path.dirname(lfile))
+    except OSError, e:
+        if e.errno != errno.EEXIST:
+            raise e
+
+    f = open(lfile, omode)
+    if mode != None:
+        os.chmod(lfile, mode)
+    f.write(content)
+    f.close()
 
 # get keyid from keyserver
-def getkeybyid(keyid,keyserver):
-   shcmd="""
-   k=${1} ks=${2};
-   exec 2>/dev/null
-   [ -n "$k" ] || exit 1;
-   armour=$(gpg --list-keys --armour "${k}")
-   if [ -z "${armour}" ]; then
-      gpg --keyserver ${ks} --recv $k >/dev/null &&
-         armour=$(gpg --export --armour "${k}") &&
-         gpg --batch --yes --delete-keys "${k}"
-   fi
-   [ -n "${armour}" ] && echo "${armour}"
-   """
-   args=['sh', '-c', shcmd, "export-gpg-keyid", keyid, keyserver]
-   return(subp(args)[0])
+def getkeybyid(keyid, keyserver):
+    shcmd = """
+    k=${1} ks=${2};
+    exec 2>/dev/null
+    [ -n "$k" ] || exit 1;
+    armour=$(gpg --list-keys --armour "${k}")
+    if [ -z "${armour}" ]; then
+        gpg --keyserver ${ks} --recv $k >/dev/null &&
+            armour=$(gpg --export --armour "${k}") &&
+            gpg --batch --yes --delete-keys "${k}"
+    fi
+    [ -n "${armour}" ] && echo "${armour}"
+    """
+    args = ['sh', '-c', shcmd, "export-gpg-keyid", keyid, keyserver]
+    return(subp(args)[0])
 
-def subp(args, input=None):
+def subp(args, linput = None):
     s_in = None
-    if input is not None:
+    if linput is not None:
         s_in = subprocess.PIPE
-    sp = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=s_in)
-    out,err = sp.communicate(input)
+    sp = subprocess.Popen(args, stdout = subprocess.PIPE,
+                          stderr = subprocess.PIPE, stdin = s_in)
+    out, err = sp.communicate(linput)
     if sp.returncode is not 0:
-        raise subprocess.CalledProcessError(sp.returncode,args)
-    return(out,err)
+        raise Exception("Failed to execute %s (%s)" % (args, sp.returncode))
+    return(out, err)
 
 def render_to_file(template, outfile, searchList):
-    t = Template(file='/etc/cloud/templates/%s.tmpl' % template, searchList=[searchList])
+    t = Template(file = '/etc/cloud/templates/%s.tmpl' % template,
+                 searchList=[searchList])
     f = open(outfile, 'w')
     f.write(t.respond())
     f.close()
@@ -126,11 +133,11 @@
 # returns boolean indicating success or failure (presense of files)
 # if files are present, populates 'fill' dictionary with 'user-data' and
 # 'meta-data' entries
-def read_optional_seed(fill,base="",ext="", timeout=2):
+def read_optional_seed(fill, base = "", ext = "", timeout = 2):
     try:
-        (md,ud) = read_seeded(base,ext,timeout)
-        fill['user-data']= ud
-        fill['meta-data']= md
+        (md, ud) = read_seeded(base, ext, timeout)
+        fill['user-data'] = ud
+        fill['meta-data'] = md
         return True
     except OSError, e:
         if e.errno == errno.ENOENT:
@@ -139,9 +146,9 @@
     
 
 # raise OSError with enoent if not found
-def read_seeded(base="", ext="", timeout=2):
+def read_seeded(base = "", ext = "", timeout = 2):
     if base.startswith("/"):
-        base="file://%s" % base
+        base = "file://%s" % base
 
     if base.find("%s") >= 0:
         ud_url = base % ("user-data" + ext)
@@ -151,20 +158,21 @@
         md_url = "%s%s%s" % (base, "meta-data", ext)
 
     try:
-        md_resp = urllib2.urlopen(urllib2.Request(md_url), timeout=timeout)
-        ud_resp = urllib2.urlopen(urllib2.Request(ud_url), timeout=timeout)
+        socket.setdefaulttimeout(timeout)
+        md_resp = urllib2.urlopen(urllib2.Request(md_url))
+        ud_resp = urllib2.urlopen(urllib2.Request(ud_url))
 
         md_str = md_resp.read()
         ud = ud_resp.read()
         md = yaml.load(md_str)
 
-        return(md,ud)
+        return(md, ud)
     except urllib2.HTTPError:
         raise
     except urllib2.URLError, e:
-        if isinstance(e.reason,OSError) and e.reason.errno == errno.ENOENT:
-           raise e.reason 
+        if isinstance(e.reason, OSError) and e.reason.errno == errno.ENOENT:
+            raise e.reason
         raise e
 
-def logexc(log,lvl=logging.DEBUG):
-    log.log(lvl,traceback.format_exc())
+def logexc(log, lvl = logging.DEBUG):
+    log.log(lvl, traceback.format_exc())
