2013年5月10日 星期五

Python: getopt範例



#!/usr/bin/env python
#
# 1. scp the compiled rpm tarball to the hosts we want to deploy
# 2. then extract it
# 3. install it

import sys
from getopt import getopt
from getopt import GetoptError
from fabric.api import env, run

def usage():
    print "Usage: %s -h <deploy-host> (-f <file> | -e <cmd>)" % sys.argv[0]
    print "       %s -H <deploy-host-file> (-f <file> | -e <cmd>)" % sys.argv[0]
    print "OPTIONS:"
    print "    -h, --host: host list"
    print "    -H, --hostfile: host list file"
    print "    -f, --file: deployfile"
    print "    -e, --exec: command execution"
    print "    --help, print information"


def main():
    try:
        """
              h:  H:  f: e: 加上冒號(:)代表是option後面要加上參數的意思
              若只有選項而沒有在後面接上冒號,例如:  "v" ,則是代表該選項後面不需要接上參數
             
        """
        opts, args = getopt(sys.argv[1:], "h:H:f:e:", ["help","host=","hostfile=","file=","exec="])
        for opt,arg in opts:
            if opt in ("-h","--host"):
                env.hosts = []
                print a
            elif opt in ("-H","--hostfile"):
                env.hosts = []
                print arg
            elif opt in ("-f","--file"):
                pass
            elif opt in ("-e","--exec"):
                pass
            else:
                Usage()
                sys.exit(1)
    except GetoptError:
        print "Error: GetoptError!"
        usage()
        sys.exit(1)


if "__main__" == __name__:
    main()

沒有留言:

張貼留言