python argparse例子
短信预约 -IT技能 免费直播动态提醒
arg_1
#!/usr/bin/python
#coding=utf-8
import argparse
def parse_args():
description = "usage: % prog[options]"
parser = argparse.ArgumentParser(description=description)
parser.add_argument('addresses', nargs='*', help='help')
parser.add_argument('filename', help='help')
parser.add_argument('-p', '--port', type=int, help='help')
parser.add_argument('--iface', help=help, default='localhost')
parser.add_argument('--delay', type=float, help=help, default=.7)
parser.add_argument('--bytes', type=int, help=help, default=10)
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
for address in args.addresses:
print 'The address is : %s .' % address
print 'The filename is : %s .' % args.filename
print 'The port is : %d.' % args.port
print 'The interface is : %s.' % args.iface
print 'The number of seconds between sending bytes : %f' % args.delay
print 'The number of bytes to send at a time : %d.' % args.bytes
#-p 22 --delay 1.2 127.0.0.1 172.16.55.67 poetry/ecstasy.txt
2.arg_2
#!/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:\n If 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[i] is None:
del args[i]
else:
n += 1
if n > 1:
print('\n Only 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
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341