1

我想要一个布尔标志和一个为我的命令提供 n 个参数的选项。所需的示例用法:

python manage.py my_command --all # Execute my_command with all id's

python manage.py my_command --ids id1 id2 id3 ... # Execute my_command with n ids

python manage.py my_command --all --ids id1 id2 id3 ... # Throw an error

我的函数现在看起来像这样(如果两者都提供,函数的主体也有抛出错误的逻辑):

@my_command_manager.option("--all", dest="all_ids", default=False, help="Execute for all ids.")
@my_command_manager.option("--ids", dest="ids", nargs="*", help="The ids to execute.")
def my_command(ids, all_ids=False): #do stuff

这适用于 --ids 选项,但 --all 选项说:error: argument --all: expected one argument

TLDR:我怎样才能同时拥有选项和命令?

4

1 回答 1

5

试试 action='store_true'

例子:

from flask import Flask
from flask.ext.script import Manager

app = Flask(__name__)
my_command_manager = Manager(app)

@my_command_manager.option(
    "--all",
    dest="all_ids",
    action="store_true",
    help="Execute for all ids.")
@my_command_manager.option(
    "--ids",
    dest="ids",
    nargs="*",
    help="The ids to execute.")
def my_command(ids, all_ids):
    print(ids, all_ids)


if __name__ == "__main__":
    my_command_manager.run()
于 2015-09-11T14:44:49.867 回答