教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 python getopt模块怎么用?

python getopt模块怎么用?

发布时间:2020-12-06   编辑:jiaochengji.com
教程集为您提供python getopt模块怎么用?等资源,欢迎您收藏本站,我们将为您提供最新的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

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

您可能感兴趣的文章:
python getopt模块怎么用?
python怎么升级模块
怎样添加新的python模块
python怎么查看安装的模块有哪些
python导入模块的关键字是什么
Python中怎么引入第三方模块
python怎么使用模块中的类
Python自定义模块
python随机数模块怎么导入
PEAR:常用模块

[关闭]
~ ~