python argparse例子

本文介绍使用Python的argparse模块来解析命令行参数的方法。通过两个示例展示了如何定义和处理命令行输入,包括基本参数、选项参数及分组参数等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. arg_1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/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=inthelp='help')
    parser.add_argument('--iface'help=help, default='localhost')
    parser.add_argument('--delay'type=floathelp=help, default=.7)
    parser.add_argument('--bytes'type=inthelp=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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/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
    = 0
    for in ('cmd''put''get'):
        if in args:
            if args[i] is None:
                del args[i]
            else:
                += 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



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/2055878,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值