python中getopt模块如何使用

小编给大家分享一下python中getopt模块如何使用,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

实例

假定我们创建这样一个脚本,可以通过命令行向脚本文件传递两个文件名,同时我们通过另外一个选项查看脚本的使用。

脚本使用方法如下:

usage: test.py -i <inputfile> -o <outputfile>

test.py 文件代码如下所示:

import sys, getopt
 
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print '输入的文件为:', inputfile
   print '输出的文件为:', outputfile
 
if __name__ == "__main__":
   main(sys.argv[1:])

执行以上代码,输出结果为:

$ python test.py -h
usage: test.py -i <inputfile> -o <outputfile>
 
$ python test.py -i inputfile -o outputfile
输入的文件为: inputfile
输出的文件为: outputfile

看完了这篇文章,相信你对python中getopt模块如何使用有了一定的了解,想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!