Argparse - 如果提供了其他参数,则跳过一个参数

2024-10-03 06:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

它现在通过以下方式传递参数:

./Converter.py -input publikey.pem

代码如下:

^{pr2}$

我还希望脚本在没有公钥.pem文件时工作,在这种情况下,用户需要按如下方式输入n和{}:

^{3}$

我使用的是argparse,基本上现在Python正在从.pem文件中提取{}和{}。在

但是我希望argparse在用户提供n和{}时绕过此提取


Tags: 文件用户py脚本input参数方式密钥
2条回答
#!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

对于文件输入:

^{pr2}$

对于变量输入:

./Converter.py -ne 4 5

只需为-n-e添加可选关键字参数

parser.add_argument('-n', type=int)
parser.add_argument('-e', type=int)

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

相关问题 更多 >