简体   繁体   English

如何在另一个 python 脚本中调用 manage.py?

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

I have a shell script that calls./manage.py a few times, and would like to create the same functionality within a python 3.9.2 script.我有一个 shell 脚本调用 ./manage.py 几次,并希望在 python 3.9.2 脚本中创建相同的功能。 I have tried subprocess.run and os.system but get hung up for various reasons.我尝试过 subprocess.run 和 os.system 但由于各种原因挂断了电话。 Currently the shell script looks like目前 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

... 

It takes time to dissect the custom management commands suggested below, so I will need to formulate a timeline for management approval.剖析下面建议的自定义管理命令需要时间,因此我需要制定管理批准的时间表。 Does anyone have an explanation of how Django attempts to tackle security implications with this?有没有人解释 Django 如何尝试解决安全隐患? We need a quick fix for dev and some pointers on prod.我们需要一个快速修复 dev 和一些关于 prod 的指针。 This is what we are looking for down and dirty time being, so if anyone has a working example that would be awesome!这就是我们正在寻找的肮脏和肮脏的时间,所以如果有人有一个很棒的工作示例!

# `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")

Maybe we just need a link on how to call python script from python scripts, and a nudge on how to break processes down to get the solution underway ourselves.也许我们只需要一个关于如何从 python 脚本调用 python 脚本的链接,以及如何分解流程以便我们自己进行解决方案的提示。 Thanks ahead of time for your consideration.提前感谢您的考虑。

As of Django 3.2, you can use call_command to run manage.py scripts:从 Django 3.2 开始,您可以使用call_command运行 manage.py 脚本:

from django.core import management

management.call_command('makemigrations')

You can also specify if the session should be interactive and use additional command arguments.您还可以指定 session 是否应该是交互式的,并使用附加命令 arguments。

https://docs.djangoproject.com/en/3.2/ref/django-admin/#django.core.management.call_command 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