On 12/06/2012 10:58 AM, Chris Angelico wrote:
On Fri, Dec 7, 2012 at 12:33 AM, Thomas Rachel
<nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa...@spamschutz.glglgl.de>
wrote:
Am 06.12.2012 09:49 schrieb Bruno Dupuis:

The point is Exceptions are made for error handling, not for normal
workflow. I hate when i read that for example:

      try:
          do_stuff(mydict[k])
      except KeyError:
          pass
I would do

     try:
         value = mydict[k]
     except KeyError:
         pass
     else:
         do_stuff(k)

Why? Because do_stuff() might raise a KeyError, which should not go
undetected.
(Assuming first off that you meant "do_stuff(value)", not
"do_stuff(k)", in that last line)

That has quite different functionality, though. The original wouldn't
have called do_stuff at all if k is not in dict, behaviour which is
matched by both his EAFP and his LBLY. But your version, in the event
of a KeyError, will call do_stuff with the previous value of value, or
raise NameError if there is no such previous value. I don't think
that's intentional.

The only way around it that I can see is an extra condition or jump -
something like:

def call_if_present(mydict,k,do_stuff):
     """Equivalent to
     do_stuff(mydict[k])
     if the key is present; otherwise, does not call do_stuff, and
returns None."""
     try:
         value = mydict[k]
     except KeyError:
         return
     return do_stuff(value)

It'll propagate any other exceptions from the subscripting (eg
TypeError if you give it a list instead of a dict), and any exceptions
from do_stuff itself. But it's getting a bit unwieldy.

ChrisA
Ok, is seems like my example code, don't like :). Is ok, it was a poor example.
This a more complex example that create a python daemons process.
In these case you see the help of try catch. To watch an Operating system problem (80% of the cases), when the fork is created. Or you can initialize a logging (in the catch statement)
and watch the log file with tail -f.


import sys, os
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
    # Perform first fork.
    try:
        pid = os.fork( )
        if pid > 0:
            sys.exit(0) # Exit first parent.
    except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)
# Decouple from parent environment.
    os.chdir("/")
    os.umask(0)
    os.setsid( )
# Perform second fork.
    try:
        pid = os.fork( )
        if pid > 0:
            sys.exit(0) # Exit second parent.
    except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)
# The process is now daemonized, redirect standard file descriptors.
    for f in sys.stdout, sys.stderr: f.flush( )
    si = file(stdin, 'r')
    so = file(stdout, 'a+')
    se = file(stderr, 'a+', 0)
    os.dup2(si.fileno( ), sys.stdin.fileno( ))
    os.dup2(so.fileno( ), sys.stdout.fileno( ))
    os.dup2(se.fileno( ), sys.stderr.fileno( ))

Or imagine that you are manage master-slave's connections (for examples to an ldap databse - or a monitor system tools), you can use try catch. If all the server's are down, maybe you want to be inform about it, you can put a function to send a email to your account

In simple works try: catch is 'GOOD'.

ipserver = {"192.168.1.13": ["monitoreo", 22],
"192.168.1.18": ["usuarios-dns", 22, 53, 139, 389, 445, 631, 3306, 4900, 8765], "192.168.1.72": ["sistemas-ldap", 22, 80, 139, 389, 445, 631, 3306, 4900, 8765],
            "192.168.1.74": ["terminales", 22,139, 445, 389, 4900],
            "192.168.1.80": ["backup", 22, 139, 445],
            "192.168.1.1": ["router", 21, 22, 25, 80, 110, 143, 465, 3128],
            "192.168.1.90": ["router", 5900]
            }

def portstatus(self, **kwargs):
        ports = kwargs.get("ports")
        server = kwargs.get("server")
        if len(ports) > 0:
            logging.info("chequeando puertos %s" % server)
            for a in ports:
                try:
                    sock = socket()
                    sock.connect((server,a))
                    sock.close
                except:
                    logging.info("informando errores en puerto %s" % a)
                    today = str(datetime.today())
subprocess.Popen("for a in $(seq 1 15); do beep; done", shell=True) self.sendreport(ip=server, server=server, cuerpo="El puerto %s esta caido en %s - %s" % (a, server, today), asunto="El puerto %s esta caido en %s - %s" % (a, server, today))
        else:
            logging.info("no hay puertos que chequear")







--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to