繁体   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