7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Djangoのカスタムコマンドをソース内から呼び出して、戻り値を取得する方法

Last updated at Posted at 2019-03-06

やりたいこと

Djangoのカスタムコマンドを作成して「python manage.py custom_command_name」というように呼び出していましたが、とある事情でDjangoソース内のpythonファイルからカスタムコマンドを実行し、かつ戻り値を取得することになりました。

意外と日本語のサイトには載っていなかったので記事にしておきます。

pythonファイルへの記述方法

「custom_command_name」という仮のDjangoカスタムコマンドを呼び出すには以下のように記述します。
これでカスタムコマンドが実行され、変数「result」にコマンドからの戻り値が返却されます。

call_command_sample.py
from django.core import management
result = management.call_command('custom_command_name')

【参考】コマンドを呼び出せるけれど推奨されない方法(戻り値も返却されない)

参考情報ですが,参考文献欄に記載したDjango公式ドキュメントには以下のとおり記載されています。

カスタム管理コマンドを実行するためにコード中から execute() を直接呼び出す事は避けてください。代わりに call_command() を利用してください。

execute_from_command_lineというメソッドでも以下のようにカスタムコマンドを呼び出せますが、内部でexecute()を呼び出しているので避けた方が良さそうです。

from django.core.management import execute_from_command_line
execute_from_command_line(['', 'custom_command_name'])

詳細は参考文献を参照してください。

参考文献

◆Django公式ドキュメント
カスタム django-admin コマンドの実装「コード中での管理コマンドの呼び出し」という欄に記載されています。
https://docs.djangoproject.com/ja/2.1/howto/custom-management-commands/

※execute_from_command_lineがexecute()を呼び出していることがわかるドキュメントです。参考程度に。
Code source de django.core.management
https://docs.djangoproject.com/fr/1.8/_modules/django/core/management/

◆stack overflow
「Can Django manage.py custom commands return a value? How, or why not?」
(Djangoのカスタムコマンドは戻り値を返却できますか?その方法と、さもなければできない理由は?)
https://stackoverflow.com/questions/22571320/can-django-manage-py-custom-commands-return-a-value-how-or-why-not

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?