Python:使用argparse处理多个标志

时间:2017-10-22 15:52:54

标签: python argparse

当我执行python myscript.py -i -i myfile.txt时 输出应为:

 info from file

 info from file

因此,每当遇到标志时,即使输出相同的数据,也会执行一些代码。

目前它只是打印出来:

来自档案

的信息
parser = argparse.ArgumentParser()
parser.add_argument('-i', help="info", action='store_true')
parser.add_argument('filename', nargs='+')
results = parser.parse_args()

if results.i:
    print("info from file")

2 个答案:

答案 0 :(得分:0)

我的意思是我猜你可以做这样的事情(如果我正确理解你的问题的话):

import sys
import argparse


def parse_i(args, to_parse):
    times_counted = 0
    for arg in args:
        if arg == to_parse:
            times_counted += 1
    return times_counted

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('-i', help="info", action='store_true')
    parser.add_argument('filename', nargs='+')
    results = parser.parse_args()

    for _ in range(0, parse_i(sys.argv, "-i")):
        if results.i:
            print("info from file")

一个例子是:

root@baal-Aspire-5733Z:~/bin/python/zeus-scanner# python file.py file -i 
info from file
root@baal-Aspire-5733Z:~/bin/python/zeus-scanner# python file.py file -i -i
info from file
info from file
root@baal-Aspire-5733Z:~/bin/python/zeus-scanner# python file.py file -i -i -i
info from file
info from file
info from file
root@baal-Aspire-5733Z:~/bin/python/zeus-scanner# python file.py file -i -i -i -i
info from file
info from file
info from file
info from file
root@baal-Aspire-5733Z:~/bin/python/zeus-scanner# 

答案 1 :(得分:0)

使用'count'操作而不是'store_true':

In [373]: parser = argparse.ArgumentParser()
In [374]: parser.add_argument('filename', nargs='+');
In [375]: parser.add_argument('-i', action='count');
In [376]: args = parser.parse_args('-i -i myfile.txt'.split())

In [377]: print(args)
Namespace(filename=['myfile.txt'], i=2)

In [378]: for i in range(args.i): print(args.filename)
['myfile.txt']
['myfile.txt']

没有-i

In [379]: args = parser.parse_args('myfile.txt'.split())
In [380]: print(args)
Namespace(filename=['myfile.txt'], i=None)

使用默认None,您需要抓住None案例:

if args.i:
    # do the rest

将默认值设置为0将简化测试:

parser.add_argument('-i', action='count', default=0);