1.使用getopt获取运行python而文件时的命令行选项和参数
#!/usr/bin/python # coding: UTF-8 import sys import getopt import os import commands def usage(): ''' @summary: the usage @param : None @return: None ''' print """ The usage of the commands: -s sql_name e.g. xxxxx -f faxtor e.g. xxxxx -p main.py e.g. python get_value.py -s xxxx -f xxxx -p ~/main.py """ def print_help_exit(): ''' @summary: print the help @param : None @return: None ''' usage() sys.exit(-1) def parse_options(): ''' @summary: get the external afferent parameters @param : None @return: None ''' rs = {} try: opts, args = getopt.getopt(sys.argv[1:], 's:f:p:') print '**************************the input is: {0} {1}'.format(opts, args) if len(opts) == 3: for name, value in opts: if name in ("-h"): print_help_exit() elif name in ("-s"): if (value != None): rs['mysql'] = value else: print "You did not give mysql_name" elif name in ("-f"): if (value != None): rs['factor'] = value else: print "You did not give the key" elif name in ("-p"): if (value != None): rs['path'] = value else: print "You did not give the key" else: print_help_exit() else: print_help_exit() except getopt.GetoptError: print_help_exit() return rs if __name__ == '__main__': options = parse_options() print options