20

I would like to execute a command via Django's manage.py shell function solely from the command line

e.g.

manage.py shell -c "from myapp import models; print models.MyModel.some_calculation()"

the came way you might use the -c option with the normal Python interpreter

e.g.

python -c "print 'hello world'"

However, I don't see an equivalent -c option for manage.py shell. Is there a way to do this?

asked Jan 25, 2011 at 18:59
2
  • Please don't. Please write a two-line script file. Commented Jan 25, 2011 at 19:05
  • 1
    see custom admin commands Commented Jan 25, 2011 at 19:05

3 Answers 3

46

Pipe it ;)

echo "print('hello world')" | python manage.py shell
Jan Kyu Peblik
1,55515 silver badges22 bronze badges
answered Aug 5, 2013 at 20:41
Sign up to request clarification or add additional context in comments.

4 Comments

or if you want to use a file: cat my_script.py | python manage.py shell
I'm not sure why, but that isn't working for me. I'm forced to use echo "$(cat my_script.py)" | python manage.py shell instead.
Correction, indentation doesn't work with IPython, so to force the standard prompt: ... | python manage.py shell -i python
Make sure you include a \n at the end (with echo -e if necessary).
6

Not like that. But it is easy enough to write a standalone script for Django.

answered Jan 25, 2011 at 19:05

1 Comment

Links tend to expire... code example here is better.
0

For anyone new coming to this question: Since Django 1.10, the -c/--command is there, and it works exactly like you'd expect. From the official docs:

Lets you pass a command as a string to execute it as Django, like so:

django-admin shell --command="import django; print(django.__version__)"
answered May 16, 2024 at 7:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.