【发布时间】:2020-03-22 09:20:52
【问题描述】:
我正在编写一个脚本来搜索因式分解的数字。
我希望我的脚本接受 1 或 3 参数,它应该只适用于:
python myscript.py -ipython 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