为什么我的程序在 while 循环中直接跳到 else 块(得到“您选择了不可用的选项!正在退出...”语句),而不是在提示用户选择选项时初始化函数?无论我输入“Q”、“q”、“Z”、“z”、“X”、“x”或任何其他字母。这是我第一次使用 argparse 模块,因此感谢您的理解。
import sys, argparse
from functions import get_expired_OINs, get_OINs, download_certs
def initialize(choice):
print("What would you like to do today? \n"
"Press X to check all expired certificates \n"
"Press Z to only download certificates for selected OIN numbers \n"
"or press Q to exit. \n"
"")
while True:
choice = input("My choice: ")
if choice.upper() == args.Q:
sys.exit()
elif choice.upper() == args.X:
get_expired_OINs()
download_certs()
break
elif choice.upper() == args.Z:
get_OINs()
download_certs()
break
else:
print("You've chosen unavailable option! Exiting...")
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-q',
type=str,
dest='Q',
help='To quit the program'
)
parser.add_argument(
'-x',
type=str,
dest='X',
help='To check for expired AS certificates'
)
parser.add_argument(
'-z',
type=str,
dest='Z',
help='To check AS certificates as needed'
)
args = parser.parse_args()
# print(args) < -- here I get object: Namespace(Q=None, X=None, Z=None)
initialize(args)
当 while 循环改为以下时:
while True:
choice = input("My choice: ")
if choice.upper() == 'Q':
sys.exit()
elif choice.upper() == 'X':
get_expired_OINs()
download_certs()
break
elif choice.upper() == 'Z':
get_OINs()
download_certs()
break
else:
print("You've chosen unavailable option! Exiting...")
sys.exit()
该程序按预期工作,但我想将其与 argparse 模块绑定。
我假设您想使用
argparse
来替换对 input
的调用。您的三个选项都应设置相同的目的地,只是具有不同的常量。
import sys, argparse
from functions import get_expired_OINs, get_OINs, download_certs
def initialize(choice):
print("What would you like to do today? \n"
"Press X to check all expired certificates \n"
"Press Z to only download certificates for selected OIN numbers \n"
"or press Q to exit. \n"
"")
while True:
choice = args.choice
if choice == 'Q':
sys.exit()
elif choice = 'X':
get_expired_OINs()
download_certs()
break
elif choice == 'Z':
get_OINs()
download_certs()
break
else:
print("You've chosen unavailable option! Exiting...")
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-q',
action='store_const',
const='Q',
dest='choice',
help='To quit the program'
)
parser.add_argument(
'-x',
action='store_const',
const='X',
dest='choice',
help='To check for expired AS certificates'
)
parser.add_argument(
'-z',
action='store_const',
const='Z',
dest='choice',
help='To check AS certificates as needed'
)
args = parser.parse_args()
initialize(args)