【问题标题】:Django call command with parameters带参数的Django调用命令
【发布时间】:2020-03-07 21:25:03
【问题描述】:

我有一个带有以下参数解析器部分的管理命令:

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--out', action='store', dest='out', required=True)
        parser.add_argument('--todos', action='store', dest='todos', \
                required=True, nargs='+')
        parser.add_argument('--filter', action='store', dest='filter')
        parser.add_argument('--list', action='store', dest='list')
        parser.add_argument('--add_id', action='store_true', dest='add_id')

。我正在尝试从视图/外壳调用此命令,但不起作用:

from django.core.management import call_command
call_command('prg_name', out='/tmp/111.txt')

,但是我收到以下错误:argument --out is required

程序有点旧: 蟒蛇:2.7 Django:1.11.16

.

我应该如何使用这个旧布局调用带有参数的 call_command?

奇怪的是,如果我这样做:

dt = {'--out=/tmp/111.txt': sth}
call_command(prg_name, *dt)

它有效,但我无法为 --todos 定义更多价值。

【问题讨论】:

  • 这里的sth 是什么?
  • 一些随机值。只是为了让工作成为字典。
  • 但是在这里你执行sequence unpacking(只有一个星号*,而不是多个),因此它只会查看字典的键,但你可以传递一个元组、列表、任何可迭代的对象。

标签: django python-2.7


【解决方案1】:

您可以将任意数量的字符串传递给命令:

call_command(prg_name, '--out=/tmp/111.txt', <b>'--todos', '8', '12', '105', '51'</b>)

如果您从命令行调用程序,您可以将它们视为传递给程序的参数。

【讨论】:

  • 嗯,它解决了--out的问题,但是对于--todos它只需要最新的..
  • @user2194805:你确定这不是因为你的命令本身的处理。我会觉得奇怪的是 call_command 本身就是问题,因为这基本上只是通过了这些,并由参数解析器解析:github.com/django/django/blob/master/django/core/management/…
  • @user2194805:如果从命令行运行命令会怎样?
  • 从命令行可以正常工作: python manage.py create_document --out /tmp/444 --todos 8 12 105 51 {'add_id': False, 'settings': None, 'pythonpath ':无,'verbosity':1,'traceback':False,'list':无,'filter':无,'no_color':False,'todos':['8','12','105' , '51'], 'out': '/tmp/444'}
  • @user2194805: 啊,但是你也需要这样传递。
猜你喜欢
  • 2018-11-11
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 2013-09-01
  • 2013-06-04
  • 2012-02-25
  • 2015-12-23
相关资源
最近更新 更多