最新公告
  • 欢迎您光临知事网软件APP资源下载站,一个优质的手机App应用商店和网站源码基地。欢迎加入永久SVIP
  • python getopt模块怎么用?

    正文概述 知事网   2020-11-16 11:11:08   230

    大家现正在学习命令行参吗?用没用到过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学习网 https://www.py.cn/


    知事网 » python getopt模块怎么用?

    发表评论

    还没有评论,快来抢沙发吧!

    [!--temp.right--]
    请选择支付方式
    ×
    余额支付
    ×
    微信扫码支付 0 元