How to make this simple code look better

MRAB python at mrabarnett.plus.com
Tue Oct 27 08:40:03 EDT 2015


On 2015-10-27 11:54, Ganesh Pal wrote:
> from myPopen import run
>
> def configure_network():
>      """
>      Prepare network for test
>      """
>      try:
>          cmd = ("netadm enable -p ncp DefaultFixed")
>          out, err, ret = run(cmd, timeout=60)
>          if ret != "":
>              logging.error("Can't run %s got %s (%d)!" % (cmd, err, ret))
>              return False
>          cmd = ("ipadm create-ip net3")
>          out, err, ret = run(cmd, timeout=60)
>          if ret != "":
>              logging.error("Can't run %s got %s (%d)!" % (cmd, err, ret))
>              return False
>          cmd = ("ipadm create-addr -a 192.168.84.3/24 net3")
>          out, err, ret = run(cmd, timeout=60)
>          if ret != "":
>              logging.error("Can't run %s got %s (%d)!" % (cmd, err, ret))
>              return False
>          cmd = (" route -p add default 192.168.84.1")
>          out, err, ret = run(cmd, timeout=60)
>          if ret != "":
>              logging.error("Can't run %s got %s (%d)!" % (cmd, err, ret))
>              return False
>      except Exception, e:
>          logging.exception("Failed to run %s got %s" % (cmd, e))
>          return False
>      logging.info("Configuring network .Done !!!")
>      return True
>
>
> Q1.How to make this code look better (in terms of quality)
> Q2. Iam using the except clause, just to maintain the syntax,  will
> any exception be caught in this case.
> Q3. Any other observations made
>
> Thanks,  Iam on Python 2.7 and freebsd.
>
According to the format strings, 'ret' is a number. If that's the case,
it's not a string, so ret != "" will always be true.

Why are you wrapping the command string literals in (...)? That's not
necessary.

You're doing the same thing with each of the command strings, so why
not put them into a list and then iterate over them? It'll save a lot
of duplication.




More information about the Python-list mailing list