zoukankan      html  css  js  c++  java
  • Python 获取命令行参数

    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
    View Code

    2.使用sys.argv获取运行python文件时的命令行参数

    ----aaa.py----
    import sys
    a=sys.argv[0]
    print 'sys.argv[0]:',a
    b=sys.argv
    print 'sys.argv:',b

    运行aaa.py文件:python aaa.py

    输出:sys.argv[0]: aaa.py

             sys.argv: ['aaa.py']

    运行aaa.py文件:python aaa.py aa bb cc

    输出:sys.argv[0]: aaa.py

             sys.argv: ['aaa.py', 'aa', 'bb', 'cc']

  • 相关阅读:
    SQL中UNION的使用
    [转]身份证号准确性检测
    shell中if/seq/for/while/until
    shell中数字、字符串、文件比较测试
    shell简介及变量的定义查看撤销
    grep/字符/次数匹配/锚定符/小大括号/wc/tr/cut/sort/uniq
    linux全局和个人配置文件说明
    linux文件的3个时间和7种文件类型
    linux常用配置文件和命令总结
    目录方式扩展swap分区大小
  • 原文地址:https://www.cnblogs.com/mianbaoshu/p/10967287.html
Copyright © 2011-2022 走看看