【问题标题】:Argparse :: ask 1 or 3 argumentsArgparse :: 询问 1 或 3 个参数
【发布时间】:2020-03-22 09:20:52
【问题描述】:

我正在编写一个脚本来搜索因式分解的数字。

我希望我的脚本接受 13 参数,它应该只适用于:

  • python myscript.py -i
  • python myscript.py -e -n -o

否则它应该打印--help

这是我的代码:

# --- Here we organize the choices command line aruments                
parser = argparse.ArgumentParser()                                      
parser.add_argument('-i', dest='input', help="input a pubilc key .pem file", metavar=None) 
parser.add_argument('-n', dest='modulus', help="value of modulus n (please input also -e and -o)", metavar=None)
parser.add_argument('-e', dest='exponent', help="value of exponent e (please input also -n and -o)", metavar=None)  
parser.add_argument('-o',dest='output', help="output a file name (please input also -n and -e)", metavar=None)                  
args = parser.parse_args()                                              

# --- Guide the user to the right choice ---                
if (len(sys.argv) == 1 and args.input != None):    # <-- problem must be around here I believe
    pass
elif (len(sys.argv) == 3 and args.modulus != None and args.exponent != None and args.output != None ):
    pass
else:
    parser.print_help()

但是当我首先运行 python myscript.py -i 时,它会打印 --help 然后执行代码。

它不应该打印 --help:一切都很好,我给出了 1 个参数,它是 input

【问题讨论】:

  • sys.argv[0] 始终是脚本名称。解析器查看sys.argv[1:]

标签: python if-statement scripting arguments argparse


【解决方案1】:

我会使用 argparse 的内置解析,例如使用子命令 (Python argparse mutual exclusive group) 或使用 mutually exclusive group

import argparse

def main(parser, args):
    if args.meo is not None:
        modulus, exponent, output = args.meo
    print(args)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-i", help="Public key .pem file")
    group.add_argument("-meo", nargs=3, help="Modulus, exponent and output")
    main(parser, parser.parse_args())

结果:

~ python args.py -h
usage: args.py [-h] [-i I | -meo MEO MEO MEO]

optional arguments:
  -h, --help        show this help message and exit
  -i I              Public key .pem file
  -meo MEO MEO MEO  Modulus, exponent and output

~ python args.py -i input.pem
Namespace(i='input.pem', meo=None)

~ python args.py -meo X Y Z
Namespace(i=None, meo=['X', 'Y', 'Z'])

【讨论】:

    【解决方案2】:

    您没有正确计算您的参数,并且您提供的两个命令行对您的程序无效。 argparse 正在做你告诉它的事情:你给了它两个无效的命令行,并得到了两组帮助文档。

    你有论据,而不是选项。正确的格式是

    python my_script.py -i FILE
    python my_script.py -e 3 -m 16 -o my.log
    

    第一行有 3 个参数;第二行有 7 个。另外,您需要一个 group 来正确处理这两种情况。

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2011-11-17
      • 2018-12-25
      • 2021-09-09
      • 2014-08-24
      • 2013-12-28
      • 2012-03-02
      • 1970-01-01
      相关资源
      最近更新 更多