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?

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
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.

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__)"

Comments

Your Answer

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.