【问题标题】:Flask-script add a command and an optionFlask-script 添加命令和选项
【发布时间】:2015-09-11 13:02:11
【问题描述】:

我想要一个布尔标志和一个为我的命令提供 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:如何同时拥有选项和命令?

【问题讨论】:

标签: python flask flask-script


【解决方案1】:

试试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()

【讨论】:

    猜你喜欢
    • 2011-08-25
    • 2019-08-10
    • 2022-01-15
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多