How to execute a Python script from the Django she

2019-01-04 15:53发布

I need to execute a Python script from the Django shell. I tried:

./manage.py shell << my_script.py

But it didn't work. It was just waiting for me to write something.

16条回答
Explosion°爆炸
2楼-- · 2019-01-04 16:18

Try this if you are using virtual enviroment :-

python manage.py shell

for using those command you must be inside virtual enviroment. for this use :-

workon vir_env_name

for example :-

dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

Note :- Here mysite is my website name and jango is my virtual enviroment name

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-04 16:19

@AtulVarma provided a very useful comment under the not-working accepted answer:

echo 'import myscript' | python manage.py shell
查看更多
forever°为你锁心
4楼-- · 2019-01-04 16:23

I'm late for the party but I hope that my response will help someone: You can do this in your Python script:

import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings

the rest of your stuff goes here ....

查看更多
冷血范
5楼-- · 2019-01-04 16:26

As other answers indicate but don't explicitly state, what you may actually need is not necessarily to execute your script from the Django shell, but to access your apps without using the Django shell.

This differs a lot Django version to Django version. If you do not find your solution on this thread, answers here -- Django script to access model objects without using manage.py shell -- or similar searches may help you.

I had to begin my_command.py with

import os,sys
sys.path.append('/path/to/myproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.file")
import django
django.setup()

import project.app.models
#do things with my models, yay

and then ran python3 my_command.py

(Django 2.0.2)

查看更多
登录 后发表回答