python怎么用getopt模块

511次阅读
没有评论
python怎么用getopt模块

大家现正在学习命令行参吗?用没用到过getopt呢?今天小编,就不跟大家聊很多的内容了,直接给大家介绍今天的文章主题,就是关于前文所提到的getopet,小伙伴们对此有没有什么了解呢?没有了解的小伙伴也不必担心,因为下面小编给大家浓缩了这个知识点的精华,看一遍,就可以快速上手了。

实例

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

脚本使用方法如下:

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

好啦,如果在碰到以上模块的使用方法,一定要看下这篇文章内容哦~都是所有疑难问题的解决集锦呢~小伙伴们仔细再看几遍吧,如果还想了解其他内容,就到教程中心浏览吧~

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-28发表,共计1087字。
新手QQ群:570568346,欢迎进群讨论 Python51学习