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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM