running multiple scripts -- which way is more elegant?

Stephen Bunn scbunn at sbunn.org
Mon Jun 20 00:13:04 EDT 2011


List,

  First I'm very new to Python. I usually do this kind of thing with shell
scripts, however, I'm trying to move to using python primarily so I can
learn the language.  I'm attempting to write a script that will check a
server for various configuration settings and report and/or change based on
those findings.  I know there are other tools that can do this, but for
various reasons I must script this.  I have come up with two ways to
accomplish what I'm trying to do and I'm looking for the more elegant
solution -- or if there is another solution that I have not thought of.  Any
input would be greatly appreciated and thanks for your time.

method 1:
=============
[master script]

def execute_script(cscript):
  process = subprocess.Popen(cscript, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
  output_data = process.communicate()

  if process.returncode == 0:
    return "OK"
  elif process.returncode == 90:
    return "DEFER"
  elif process.returncode == 80:
    return "UPDATED"
  else:
    return "ERROR"

if __name__ == '__main__':

  # Find all configuration scripts
  print "Searching for config scripts"
  cscripts = []
  for config_script in os.listdir(BASE_DIR + "/config.d"):
    cscripts.append(BASE_DIR + '/config.d/' + config_script)
  print "Found %d configuration scripts" % (len(cscripts))

  # Loop through scripts and execute
  for config_script in cscripts:
    action_title = "Checking %s" % (config_script[len(BASE_DIR +
'/config.d/'):])
    print "%-75.75s [  %s  ]" % (action_title,
execute_script(config_script))

[config script template]
#!/usr/bin/env python

def check():
    # do some checking
    return results

return check()



method 2:
============
[master script]
if __name__ == '__main__':

  # Find all configuration scripts
  print "Searching for config scripts"
  cscripts = []
  for config_script in os.listdir(BASE_DIR + "/config.d"):
    cscripts.append(BASE_DIR + '/config.d/' + config_script)
  print "Found %d configuration scripts" % (len(cscripts))

  # Loop through scripts and execute
  for config_script in cscripts:
    import config_script
    action_title = "Checking %s" % (config_script[len(BASE_DIR +
'/config.d/'):])
    print "%-75.75s [  %s  ]" % (action_title, config_script.check())


[config script template]
#!/usr/bin/env python

def check():
   # do some stuff
   return result  # return str OK, DEFER, UPDATED or ERROR
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110620/f93c4d5f/attachment.html>


More information about the Python-list mailing list