• 技术文章 >Python技术 >Python基础教程

    python getopt模块怎么用?

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

    实例

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

    脚本使用方法如下:

    1

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

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    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:])

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

    1

    2

    3

    4

    5

    6

    $ python test.py -h

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

      

    $ python test.py -i inputfile -o outputfile

    输入的文件为: inputfile

    输出的文件为: outputfile

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

    专题推荐:pythongetopt模块用法
    上一篇:如何掌握python中class函数用法? 下一篇:python assert函数是什么以及如何使用?

    相关文章推荐

    • python3 tkinter模块中的pick怎么用?• 如何掌握python中class函数用法?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网