首页 > 解决方案 > 如果一个 argparse 操作为真,则获取另一个值

问题描述

我是 python 新手并尝试下面的代码。我所需要的只是如果其中一个 argarse 值是真的,那么得到另一个值。

#! /home/y/bin/python3
import argparse
__author__ = "Yogesh"


parser =  argparse.ArgumentParser(description='This is demo script')
parser.add_argument('-s','--source_host', help='Source Host Name',required=True)
parser.add_argument('-d','--dest_host',help='Destination Host Name',required=True)
parser.add_argument('-n','--user_count',help="No of users to migrate",required=False)
parser.add_argument('--action', choices=['one-week', 'two-week','user-count','all-users'], default='all-users')

args = parser.parse_args()

print("Source Host:{0}".format(args.source_host))
print("Dest Host:{0}".format(args.dest_host))
if args.action == 'one-week':
    print("Migrate one week active users".format(args.action))
elif args.action == 'two-week':
    print("Migrate two week active users".format(args.action))
elif args.action == 'user-count':
    print("Mingrate user_count".format(args.action))
else:
    print("Migrate all users ".format(args.action))

我正在寻找的是如果用户计数为真,那么代码应该提示输入--user_count。非常感谢。

标签: pythonargparse

解决方案


我已经更新了条件语句。我想这就是你想要做的。

if args.action == 'one-week':
    print("Migrate one week active users".format(args.action))
elif args.action == 'two-week':
    print("Migrate two week active users".format(args.action))
elif args.action == 'user-count':
    user_count = input('Enter user count: ')
    print("Mingrate {user_count} users".format(user_count=user_count))
else:
    print("Migrate all users ".format(args.action))

推荐阅读