Argparse:如果提供了另一个参数则绕过一个参数

Argparse: bypass an argument if another argument is provided

this post 之后,我正在创建一个小的 Python 脚本,它可以输入一个 public RSA 密钥并输出一个私有 RSA 密钥。

它现在通过这种方式传递参数来工作:

./Converter.py -input publikey.pem

这是代码:

<!-- language: lang-py -->

parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='infile', help="input a .pem file which contains pubilc key")
args = parser.parse_args()
# --- Here we search for n and e ---
PublicKey = args.infile
OpenPublicKey = open(PublicKey, 'r')
ReadPublicKey = OpenPublicKey.read()
TheKey = RSA.importKey(ReadPublicKey)
n = long(TheKey.n)
e = long(TheKey.e)
print 'This is modulus n: ', n, '\n'
print 'This is public exponent e: ', e, '\n'

我还希望脚本在没有 public 密钥 .pem 文件时工作,在这种情况下,用户需要以这种方式输入 ne :

./Converter.py -n 7919 -e 65537

我正在使用 argparse,现在 Python 基本上是从 .pem 文件中提取 ne

但我希望 argparsene 由用户

提供时绕过此提取

只需为 -n-e

添加可选的关键字参数
parser.add_argument('-n', type=int)
parser.add_argument('-e', type=int)

如果 args.n and args.e 的计算结果为 True,则忽略输入参数并跳过处理它的代码。

#!python2
import argparse
from Crypto.PublicKey import RSA
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)

group.add_argument('-f','--infile', help="input a .pem file which contains pubilc key")
group.add_argument('-ne',nargs=2, help="value of n and e")

args = parser.parse_args()
# --- Here we search for n and e ---
if args.infile:
    PublicKey = args.infile
    OpenPublicKey = open(PublicKey, 'r')
    ReadPublicKey = OpenPublicKey.read()
    TheKey = RSA.importKey(ReadPublicKey)
    n = long(TheKey.n)
    e = long(TheKey.e)

else:
    n,e=map(long,args.ne)
print 'This is modulus n: ', n
print 'This is public exponent e: ', e

对于文件输入:

./Converter.py -f publickey.pem

对于变量输入:

./Converter.py -ne 4 5