简体   繁体   中英

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. I have tried subprocess.run and os.system but get hung up for various reasons. Currently the shell script looks like

./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? We need a quick fix for dev and some pointers on 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. Thanks ahead of time for your consideration.

As of Django 3.2, you can use call_command to run manage.py scripts:

from django.core import management

management.call_command('makemigrations')

You can also specify if the session should be interactive and use additional command arguments.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM