簡體   English   中英

如何在另一個 python 腳本中調用 manage.py?

[英]How can I call manage.py within another python script?

我有一個 shell 腳本調用 ./manage.py 幾次,並希望在 python 3.9.2 腳本中創建相同的功能。 我嘗試過 subprocess.run 和 os.system 但由於各種原因掛斷了電話。 目前 shell 腳本看起來像

./manage.py dump_object water_testing.watertest '*' > ./water_testing/fixtures/dump_stevens.json
./manage.py dump_object tp.eqsvc '*' >> ./water_testing/fixtures/dump_stevens.json

... 

剖析下面建議的自定義管理命令需要時間,因此我需要制定管理批准的時間表。 有沒有人解釋 Django 如何嘗試解決安全隱患? 我們需要一個快速修復 dev 和一些關於 prod 的指針。 這就是我們正在尋找的骯臟和骯臟的時間,所以如果有人有一個很棒的工作示例!

# `input` args/params are necessary
# `capture_output` is good if we need to do something with it later
# `check` the subprocess actually fired off and completed into traces are crucial.

output = subprocess.run(["manage.py"], input="dump_object water_testing.watertest '*' > ./water_testing/fixtures/dump_stevens.json", capture_output=True, text=True, check=True)

# this won't work either
os.system("python ./manage.py dump_object water_testing.watertest '*' > ./water_testing/fixtures/dump_stevens.json")

也許我們只需要一個關於如何從 python 腳本調用 python 腳本的鏈接,以及如何分解流程以便我們自己進行解決方案的提示。 提前感謝您的考慮。

從 Django 3.2 開始,您可以使用call_command運行 manage.py 腳本:

from django.core import management

management.call_command('makemigrations')

您還可以指定 session 是否應該是交互式的,並使用附加命令 arguments。

https://docs.djangoproject.com/en/3.2/ref/django-admin/#django.core.management.call_command

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM