美文网首页
python 编写命令行工具 用 argparse

python 编写命令行工具 用 argparse

作者: Joncc | 来源:发表于2020-10-21 11:47 被阅读0次
    #!/usr/bin/env python 
    # -*- coding: utf-8 -*- 
    # @Time : 2020/5/27 下午5:00 
    # @Author : Jon
    from __future__ import unicode_literals
    from __future__ import print_function
    import argparse
    import socket
    
    def parse_cmdargs(args=None, target=''):
        """
        Consume generic arguments from the start of the ``args``
        list.  Call this first to handle arguments that are not
        handled by a command description provided by the server.
    
        :returns: three tuple of ArgumentParser instance, Namespace instance
                  containing parsed values, and list of un-handled arguments
        """
        # alias: let the line-wrapping be sane
        AP = argparse.ArgumentParser
    
        # format our own help
    
        parser = AP(description='ceph command tool', add_help=False)
    
        parser.add_argument('--completion', action='store_true',
                            help=argparse.SUPPRESS)
    
        parser.add_argument('-h', '--help', help='help -h or --help',
                            action='store_true')
    
        parser.add_argument('-osd', '--osd', dest='osd',
                            help='args json {ip:iplist, ...}')
    
        parser.add_argument('-mon', '--mon', dest='mon',
                            help='args json {ip:iplist, ...}')
    
        # returns a Namespace with the parsed args, and a list of all extras
        parsed_args, extras = parser.parse_known_args(args)
    
        return parser, parsed_args, extras
    
    
    
    def _sendcmd_and_recv(ip='127.0.0.1', name=False):
        jsonargs = "{'test':'1'}"
        PORT = '8001'
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
        try:
            s.connect((ip, PORT))
            s.sendall(jsonargs)
        except Exception, reason:
                logs.debug("send message to %s,%s" % (ip, reason))
                return False
    
    
    def main():
        parser, parsed_args, childargs = parse_cmdargs()
    
        # print(parser, parsed_args, childargs)
        print('=========')
    
        if parsed_args.help:
            parser.print_help()
            print()
        if parsed_args.osd:
            print(parsed_args.osd)
        if parsed_args.mon:
            print(parsed_args.mon)
    
    
    
    
    if __name__ == '__main__':
        main()
    

    相关文章

      网友评论

          本文标题:python 编写命令行工具 用 argparse

          本文链接:https://www.haomeiwen.com/subject/rsrgahtx.html