zoukankan      html  css  js  c++  java
  • python解析命令行参数

    常常需要解析命令行参数,经常忘记,好烦,总结下来吧。

    1.Python 中也可以所用 sys 的 sys.argv 来获取命令行参数:

    sys.argv 是命令行参数列表

    参数个数:len(sys.argv)
    脚本名:    sys.argv[0]
    参数1:     sys.argv[1]

    示例代码如下:

    1 #!/usr/bin/python
    2 # -*- coding: UTF-8 -*-
    3 
    4 import sys
    5 
    6 print('参数个数为: ' + str(len(sys.argv)) + '个参数。')
    7 print("脚本名:" + sys.argv[0])
    8 for i in range(1, len(sys.argv)):
    9     print("参数" + str(i) + ': ' + sys.argv[i])

    2.getopt模块

    getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式(-)和长选项模式(--)。

    该模块提供了两个方法及一个异常处理来解析命令行参数。

    getopt.getopt 方法

    getopt.getopt 方法用于解析命令行参数列表,语法格式如下:

    getopt.getopt(args, options[, long_options])

    方法参数说明:

    • args: 要解析的命令行参数列表。

    • options: 以列表的格式定义,options后的冒号(:)表示该选项必须有附加的参数,不带冒号表示该选项不附加参数。

    • long_options: 以字符串的格式定义,long_options 后的等号(=)表示如果设置该选项,必须有附加的参数,否则就不附加参数。

    • 该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有'-'或'--'的参数。

    另外一个方法是 getopt.gnu_getopt,这里不多做介绍。


    Exception getopt.GetoptError

    在没有找到参数列表,或选项的需要的参数为空时会触发该异常。

    异常的参数是一个字符串,表示错误的原因。属性 msg 和 opt 为相关选项的错误信息。

     示例代码如下:

     1 # -*- coding:utf-8 -*- 
     2 
     3 import sys, getopt
     4 
     5 def main(argv):
     6     inputfile = ""
     7     outputfile = ""
     8 
     9     try:
    10         # 这里的 h 就表示该选项无参数,i:表示 i 选项后需要有参数
    11         opts, args = getopt.getopt(argv, "hi:o:",["infile=", "outfile=", "version", "help"])
    12         #第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有'-'或'--'的参数
    13     except getopt.GetoptError:
    14         print('test_arg.py -i <inputfile> -o <outputfile>')
    15         print('or: test_arg.py --infile=<inputfile> --outfile=<outputfile>')
    16         print('or: test_arg.py --version --help')
    17         sys.exit(2)
    18 
    19     if len(args) > 0:    #表示有未识别的参数格式
    20         print('test_arg.py -i <inputfile> -o <outputfile>')
    21         print('or: test_arg.py --infile=<inputfile> --outfile=<outputfile>')
    22         print('or: test_arg.py --version --help')
    23         sys.exit(1)
    24     else:
    25         for opt, arg in opts:
    26             if opt in ("-h", "--help"):
    27                 print('test_arg.py -i <inputfile> -o <outputfile>')
    28                 print('or: test_arg.py --infile=<inputfile> --outfile=<outputfile>')
    29                 print('or: test_arg.py --version --help')
    30     
    31                 sys.exit()
    32             elif opt in ("-i", "--infile"):
    33                 inputfile = arg
    34             elif opt in ("-o", "--outfile"):
    35                 outputfile = arg
    36             elif opt in ("--version"):
    37                 print('0.0.1')
    38                 sys.exit()
    39 
    40     print('Input file : ', inputfile)
    41     print('Output file: ', outputfile)
    42 
    43 if __name__ == "__main__":
    44     main(sys.argv[1:])
  • 相关阅读:
    eclipse中的Invalid text string (xxx).
    在jsp文件中出现Unknown tag (c:out)
    eclipse 界面复原
    ecilpse 纠错插件
    Multiple annotations found at this line:- The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
    Port 8080 required by Tomcat v9.0 Server at localhost is already in use. The server may already be running in another process, or a system process may be using the port.
    调用第三方https接口
    调用第三方http接口
    创建带值枚举
    spring整合redis之Redis配置文件
  • 原文地址:https://www.cnblogs.com/hushaojun/p/7977572.html
Copyright © 2011-2022 走看看