前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python命令行参数模块argpars

python命令行参数模块argpars

作者头像
py3study
发布2020-01-10 16:06:32
5090
发布2020-01-10 16:06:32
举报
文章被收录于专栏:python3python3python3

argparse

说明

  • 处理可选参数与位置参数
  • handles both optional and positional arguments
  • 产生标准化的帮助信息
  • produces highly informative usage messages
  • 支持调度子分器的解析器
  • supports parsers that dispatch to sub-parsers

Example code

    # 初始化一个实例
    parser = argparse.ArgumentParser(
        description='sum the integers at the command line')

    # 添加位置参数, 类型为int    
    parser.add_argument(
        'integers', metavar='int', nargs='+', type=int,
        help='an integer to be summed')

    # 添加可选参数,默认为标准输出,类型为FileType文件类    
    parser.add_argument(
        '--log', default=sys.stdout, type=argparse.FileType('w'),
        help='the file where the sum should be written')

    # 解析    
    args = parser.parse_args()
    # Namespace(count='50', echo='good', host='172.168.100.1')

    args.log.write('%s' % sum(args.integers))
    args.log.close()

Example code

#coding:utf8

import argparse

class Args(object):

    def __init__(self):
        parser = argparse.ArgumentParser(
            description="A test network port tool"
        )
        parser.add_argument(
            "echo",
            help="echo info."
        )
        parser.add_argument(
            "-H", "--host",
            help="ipaddr or domain addr."
        )
        parser.add_argument(
            "-c", "--count",
            help="connect counts"
        )
        args = parser.parse_args()
        self.args = args

    def cc(self):
        print self.args
        print "args host: ", self.args.host
        print "args count: " ,self.args.count

if __name__ == "__main__":
    a = Args()
    a.cc()

Result

➜  test git:(master) ✗ python argpar.py good -H 172.168.100.1 -c 50
Namespace(count='50', echo='good', host='172.168.100.1')
args host:  172.168.100.1
args count:  50
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • argparse
    • 说明
      • Example code
        • Example code
          • Result
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档