【问题标题】:Executing a Django Shell Command from the Command Line从命令行执行 Django Shell 命令
【发布时间】:2011-06-15 10:08:50
【问题描述】:

我想仅从命令行通过 Django 的 manage.py shell 函数执行命令

例如

manage.py shell -c "from myapp import models; print models.MyModel.some_calculation()"

您可以在普通 Python 解释器中使用 -c 选项

例如

python -c "print 'hello world'"

但是,我没有看到 manage.py shell 的等效 -c 选项。有没有办法做到这一点?

【问题讨论】:

标签: python django django-shell


【解决方案1】:

Pipe它;)

echo "print('hello world')" | python manage.py shell

【讨论】:

  • 或者如果你想使用文件:cat my_script.py | python manage.py shell
  • 我不知道为什么,但这对我不起作用。我不得不改用echo "$(cat my_script.py)" | python manage.py shell
  • 更正,缩进不适用于 IPython,所以强制标准提示:... | python manage.py shell -i python
  • 确保在末尾添加\n(如有必要,添加echo -e)。
【解决方案2】:

不是那样的。但是写一个standalone script for Django很容易。

【讨论】:

  • 链接往往会过期...这里的代码示例更好。