zdc253212956 发表于 2018-8-7 09:07:32

python argparse例子

#!/usr/bin/python  
# coding=utf-8
  
import argparse
  
from argparse import ArgumentParser, RawTextHelpFormatter
  

  
def get_args():
  
    """实例化类,formatter_class参数允许help信息以自定义的格式显示"""
  
    parser = ArgumentParser(description="This is a tool for execute command(s) on remote server(s) or get/put file(s) from/to the remote server(s)\nNotice: please always use '/' as path separater!!!",formatter_class=RawTextHelpFormatter,epilog="Notice:\nIf any options use more than once,the last one will overwrite the previous")
  
    remote_command = parser.add_argument_group('remote command', 'options for running remote command')
  
    remote_command.add_argument('--cmd', metavar='“COMMAND”', dest='cmd',help="command run on remote server,multiple commands sperate by ';'")
  
    sftp = parser.add_argument_group('sftp', 'options for running sftp')
  
    sftp.add_argument('--put', metavar='', help="transfer from local to remote", nargs=2)
  
    sftp.add_argument('--get', metavar='', help="transfer from remote to local", nargs=2)
  
    global args
  
    args = vars(parser.parse_args())
  
    print args
  
    n = 0
  
    for i in ('cmd', 'put', 'get'):
  
      if i in args:
  
            if args is None:
  
                del args
  
            else:
  
                n += 1
  
    if n > 1:
  
      print('\nOnly one of the "--cmd --put --get" can be used!')
  
      exit(10)
  

  
if __name__ == '__main__':
  
    get_args()
  
    if 'cmd' in args:
  
      echo_cmd = args['cmd']
  
      print echo_cmd
  

  
# --cmd uptime --get /home/nginx /home/nginx
页: [1]
查看完整版本: python argparse例子