python命令行模式-sys.argv &&optionparser

1.使用sys.argv

import sys

if __name__ == "__main__":
    #1.获取参数
    # E:\python_sample > python test.py 0 2 3
    # ['test.py', '0', '2', '3']
    cmd = sys.argv
    print("the input command list as below:  %s"%str(cmd))
    #2.校验是否有参数输入
    if len(cmd) < 2:
        print('No action specified.')
        sys.exit()
    #3.校验参数是否正常
    if cmd[1]==str(1):
        print(cmd[1])
    else:
        print('this parameter does not match the default type')
        sys.exit()

2.使用optionparser

from optparse import OptionParser

#1.初始化parser
parser = OptionParser()

#2.参数初始化
parser.add_option("-p", "--pdbk", action="store_true",
                  dest="pdcl",
                  default=False,
                  help="write pdbk data to oracle db")
parser.add_option("-z", "--zdbk", action="store_true",
                  dest="zdcl",
                  default=False,
                  help="write zdbk data to oracle db")
#3.获取参数
(options, args) = parser.parse_args()

#4.较验参数
if options.pdcl==True:
    print('pdcl is true')
if options.zdcl==True:
    print('zdcl is true')
    原文作者:Godric_wsw
    原文地址: https://www.jianshu.com/p/399f4f38630d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞