2012年1月30日 星期一

optparse 模組取代掉getopt舊式模組

import optparse取代import getopt


下面有事例:



# parserforoption.py
import optparse
import socket


def connectTo(toaddr,toport):
    toaddr = str(toaddr)
    toport = int(toport)
    print "Create socket objetct for {addr},port {port}".format(addr=toaddr,port=toport)
        
    s = socket.socket()
    toaddr = socket.gethostbyname(toaddr)
    
    try:
        s.connect((toaddr, toport))
        print "Connected to {addr} on {port}".format(addr=toaddr , port=toport)
        return True
    except socket.error as e:
        print "Connection to {addr} on {port} FAILED!".format(addr=toaddr,port=toport)
        return False


if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-a","--address",dest="address",default= "localhost",help="address for server",metavar="ADDRESS")
    parser.add_option("-p","--port",dest="port",default= "localhost",help="port for server",metavar="PORT")
    (options,args )= parser.parse_args()
    toaddr = options.address
    toport = options.port
    
    #if connectTo('www.google.com.tw',80):
    if connectTo(toaddr,toport):
        print "GET STATE: OK."
    else:
        print "GET STATE: FAILED."


輸出結果


C:\Python27>python parserforoption.py -h
Usage: parserforoption.py [options]


Options:
  -h, --help            show this help message and exit
  -a ADDRESS, --address=ADDRESS
                        address for server
  -p PORT, --port=PORT  port for server





C:\Python27>python parserforoption.py -a 140.112.27.28 -p 80
Create socket objetct for 140.112.27.28,port 80
Connected to 140.112.27.28 on 80
GET STATE: OK.

沒有留言:

張貼留言