更简单、更直观的语法
我是python中的argparse新手。
我的程序可以重置创建、删除或重置帐户密码。
python manager.py create <some_username> # Create a account
delete <some_username> # Delete a account
resetpw <some_username> mysql # Reset mysql pw of account
resetpw <some_username> unix # Reset unix pw of account
参数"create", "delete", "mysql"one_answers"unix"是静态的。如何在argparse中实现?
我试过了:
parser = argparse.ArgumentParser(prog='manager')
parser.add_argument('create', action='store_true', help='Create a account')
parser.add_argument('delete', action='store_true', help='Delete a account')
args = parser.parse_args()
您正在寻找子解析器:
import argparse
parser = argparse.ArgumentParser(prog='manager')
sub = parser.add_subparsers(dest='command')
sub.add_parser('create', help='Create a account')
sub.add_parser('delete', help='Delete a account')
print parser.parse_args(['create'])
# Namespace(command='create')
作为旁注,我建议你试试place或arh。它们提供了比标准argparse