2011-01-31 64 views
28

我可以移动到一个Python项目目录(例如c:\ WWW \ myproject的),然后发出使用Django:从 “蟒蛇manage.py壳” 给Python脚本

python manage.py shell 

,然后我可以使用所有从Django项目模块,说shell命令下面这段命令:

import settings 
from django.template import Template, Context 

t=Template("My name is {myname}.") 
c=Context({"myname":"John"}) 
f = open('write_test.txt', 'w') 
f.write(t.render(c)) 
f.close 

现在,当我试图在我的所有命令收集到一个python脚本,说“mytest.py”,我不能执行该脚本。我必须错过重要的事情。

我发出蟒蛇mytest.py

后来我Import error: could not import settings它是SYS道路?”

我在settings.py所在的项目目录是.....

能有人帮帮我吗?

感谢。

+0

你能发布错误吗?您最有可能有PYTHONPATH问题。由于你的问题提到了C:驱动器,我假设你在Windows上。 http://docs.python.org/using/windows.html – dicato 2011-01-31 03:55:25

+0

谢谢。错误已添加。 – john 2011-01-31 04:01:18

+0

[Django脚本访问模型对象而不使用manage.py shell]的可能重复(http://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py - 壳) – 2016-05-13 15:33:28

回答

21

尝试使用Django management command代替。

# myproject/myapp/management/commands/my_command.py 

from django.core.management.base import NoArgsCommand 
from django.template import Template, Context 
from django.conf import settings 

class Command(NoArgsCommand): 
    def handle_noargs(self, **options): 
     t=Template("My name is {myname}.") 
     c=Context({"myname":"John"}) 
     f = open('write_test.txt', 'w') 
     f.write(t.render(c)) 
     f.close 

然后(如果你按照文档),你将能够以下列方式来执行命令:

python manage.py my_command 
+0

谢谢。我会试试看。有更简单的解决方案吗? – john 2011-01-31 04:03:24

+0

看到我的其他答案,这可能只是伎俩。但是,如果你想为你的脚本提供一个整洁的地方,那么管理命令可能就是要走的路。 – 2011-01-31 04:05:39

2

导入Django的设置,使用方法:

from django.conf import settings 
11

尝试放这两行文字开头:

from django.conf import settings 
settings.configure() # check django source for more detail 

# now you can import other django modules 
from django.template import Template, Context 
23

这个方法在Django 1.4中是deprecated。使用django.conf.settings.configure()而不是 (请参阅@ adiew的答案,例如代码)。

旧方法如下。

将这个在你的脚本

from django.core.management import setup_environ 
import settings 
setup_environ(settings) 

的开始这是真正的manage.py做幕后的东西。要查看它,请查看django/core/management/__init__.py中的Django源代码。执行这些行后,所有内容都应该与./manage.py shell一样。

2

不需要手动将东西添加到您的python脚本中,也不必为了适应管理命令格式,如果这不是需要保持很长时间的事情,您可以通过运行您的应用程序来获得Django环境的所有好处与./manage.py runscript <myscript.py>

脚本...但如果你的脚本是在你的项目文件夹中,那么你可以加入这一行的python脚本的顶部:import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

1

看到https://stackoverflow.com/a/24456404/4200284的Django> = 1.7和万一有人很好地解决使用Django的配置这个工作对我来说:

import sys, os, django 

sys.path.append('/path/to/project') 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.local") # path to config 

## if using django-configurations 
os.environ.setdefault("DJANGO_CONFIGURATION", "Local") 
from configurations import importer 
importer.install() 

django.setup() ## apparently important for django 1.7 

from foo.models import Bar 

print Bar.objects.all()