方法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)

参见:http://blog.csdn.net/lwnylslwnyls/article/details/8199454

相关文章:

  • 2022-12-23
  • 2021-08-21
  • 2021-09-07
  • 2021-11-28
  • 2021-12-05
  • 2021-12-09
  • 2022-01-20
猜你喜欢
  • 2021-07-31
  • 2021-12-04
  • 2021-11-03
  • 2022-02-02
  • 2021-12-28
  • 2021-12-25
  • 2021-08-24
相关资源
相似解决方案