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']

原文地址:https://www.cnblogs.com/mianbaoshu/p/10967287.html