approach to writing functions

Terry Reedy tjreedy at udel.edu
Tue Feb 10 10:12:13 EST 2004


"Bart Nessux" <bart_nessux at hotmail.com> wrote in message
news:c0an8o$g7i$1 at solaris.cc.vt.edu...
> Paul Prescod wrote:
> > If I were you I would post one of these scripts and see if the function
> > and OO fans can make it easier to read or maintain by using structured
> > programming.
>
> OK, here is a script that works w/o OO or functions. It's very useful...
> never fails. It helps sys admins track machines that have mobile users
> who are using DHCP.
>
> #!/usr/bin/python
> #
> # Tested on Linux Machines
> # Run as cron as root
> # May work on OS X too
> #
> # Dec 29, 2003 works on Mac OSX 10.3 like this:
> # chown 'root' && chgrp 'wheel' && chmod '755'
> # place in /usr/bin
> #
>
> from email.MIMEText import MIMEText
> import smtplib
> import os
>
> u = "User" #Change This to user's name.
> f = "admin at XXX.edu"
> t = "admin at XXX.edu"
>
> fp0 = os.popen("/sbin/ifconfig en0 inet", "r")
> fp1 = os.popen("/usr/bin/uptime", "r")
> fp2 = os.popen("/usr/bin/uname -a", "r")
> fp3 = os.popen("/usr/bin/wc -l /etc/passwd", "r")
> msg = MIMEText("-- IFCONFIG --\n\n" + fp0.read() + "\n-- UPTIME --\n\n"
> +  fp1.read() + "\n-- UNAME --\n\n" + fp2.read() + "\n-- PASSWD LC
> --\n\n" + fp3.read())
> fp0.close()
> fp1.close()
> fp2.close()
> fp3.close()
>
> msg["Subject"] = "%s's ifconfig Report" % u
> msg["From"] = f
> msg["To"] = t
>
> h = "smtp.vt.edu"
> s = smtplib.SMTP(h)
> s.sendmail(f, t, msg.as_string())
> s.quit()

Your whole script is a coherent no-argument function:  create and mail a
status message.  C requires you to wrap such within the file as a
syntactically explicit 'main' function.  Python, being against busywork for
the sake of busywork, does not.

The *possible* advantage of doing something like this:

def sendreport():
  <your current code

if __name__ == '__main__':
  sendreport()

is that you could then import the module and use sendreport from another
script.  You might then parameterize it to make some of the constants like
u (user) variable.  You could then do things like

for u in userlist: sendreport(u)

But the value of adding the wrapper and boilerplate and attendant
flexibility depends on your situation.  It also rests on getting the basic
functionality correct.

[OO fans might suggest defining a stat_rep class with a send method, but I
only see that a having much value if you want the learning experience or if
you need to keep unsent messages around.]

As for the code itself.  I would probably use more mnemonic names like
f_inet, f_time, f_name, and f_user, but this is a minor stylistic nit.  I
might also read and maybe close each pipe as created, but maybe you want
the processes to run as close to simultaneous as possible.

Terry J. Reedy







More information about the Python-list mailing list