Ticket #5596: gethostbyname-exit-5596-3.patch

File gethostbyname-exit-5596-3.patch, 2.2 KB (added by Richard Wall, 8 years ago)

Updated to use task.react

  • doc/names/examples/gethostbyname.py

    === modified file 'doc/names/examples/gethostbyname.py'
     
    44# See LICENSE for details.
    55
    66"""
    7 Returns the IP address for a given hostname.
    8 To run this script:
    9 $ python gethostbyname.py <hostname>
    10 e.g.:
    11 $ python gethostbyname.py www.google.com
     7USAGE: python gethostbyname.py HOSTNAME
     8
     9Return the IP address for a given hostname. eg
     10
     11 python gethostbyname.py www.google.com
     12
     13This script does a host lookup using the default Twisted Names
     14resolver, a chained resolver, which attempts to lookup a name from:
     15 * local hosts file
     16 * memory cache of previous lookup results
     17 * system recursive DNS servers
    1218"""
    1319import sys
    14 from twisted.names import client
    15 from twisted.internet import reactor
    16 
    17 def gotResult(result):
    18     print result
    19     reactor.stop()
    20 
    21 def gotFailure(failure):
    22     failure.printTraceback()
    23     reactor.stop()
    24 
    25 d = client.getHostByName(sys.argv[1])
    26 d.addCallbacks(gotResult, gotFailure)
    27 
    28 reactor.run()
     20from twisted.names import client, error
     21from twisted.internet.task import react
     22
     23
     24def _gotResult(address, hostname):
     25    """
     26    Print the IP address or an error message if an IP address was not
     27    found.
     28    """
     29    if address:
     30        sys.stdout.write(address + '\n')
     31    else:
     32        sys.stderr.write(
     33            'ERROR: No IP adresses found for name %r\n' % (hostname,))
     34
     35
     36def _gotFailure(failure, hostname):
     37    """
     38    Print a friendly error message if the hostname could not be
     39    resolved.
     40    """
     41    failure.trap(error.DNSNameError)
     42    sys.stderr.write('ERROR: hostname not found %r\n' % (hostname,))
     43
     44
     45def main(reactor, *argv):
     46    try:
     47        hostname = argv[0]
     48    except IndexError:
     49        sys.stderr.write(
     50            __doc__.lstrip() + '\n'
     51            'ERROR: missing HOSTNAME argument\n')
     52        raise SystemExit(1)
     53
     54    d = client.getHostByName(hostname)
     55    d.addCallback(_gotResult, hostname)
     56    d.addErrback(_gotFailure, hostname)
     57    return d
     58
     59if __name__ == '__main__':
     60    react(main, sys.argv[1:])