当前位置: 移动技术网 > IT编程>脚本编程>Python > Python参数初始化_Python 命令行参数解析

Python参数初始化_Python 命令行参数解析

2017年12月18日  | 移动技术网IT编程  | 我要评论

建信优置基金,内蒙古电子地图,莴笋叶的做法

Python参数初始化_Python 命令行参数解析。

方法1:

Python有一个类可以专门处理命令行参数,先看代码:

#!/usr/bin/env python                                                                                                

# encoding: utf-8                                                                                                    from optparse import OptionParser 

                                                                                                                     

parser = OptionParser(usage="%prog [options]")

parser.add_option("-m","--machine",action="store",type="string",dest="machine",help="the machine to be check")

(options,args)=parser.parse_args()   

if options.machine:        

    print options.machine

第一行用来初始化,

-m 为参数简写,—machine 为完整参数 store意思为将该参数存储, type为存储类型。dest为存储至哪个变量,默认为完整参数名,help为帮助时显示的内容

方法2:

使用getopt模块来解析

import sys

import getopt

def TestGetOpt():

  try:

    opts, args = getopt.getopt(sys.argv[1:],'d:f:h',['days=','files=','help'])

  except getopt.GetoptError:

     usage()

     sys.exit()

  print (opts)

  print (args)

  for o, a in opts:

     if o in ("-h", "--help"):

         usage()

         sys.exit()

     elif o in ("-d", "--days"):

         day = a

     elif o in ("-f", "--files"):

         files = a

  print (day)

  print (files)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网