使用django:from“python manage.py shell”到python脚本 [英] use django: from "python manage.py shell" to python script

查看:441
本文介绍了使用django:from“python manage.py shell”到python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以移动到一个python项目目录(例如c:\www\myproject),然后发布

I can move to a python project directory (say c:\www\myproject) and then issue

   python manage.py shell

然后我可以使用django项目中的所有模块,说下面的命令从shell命令:

and then I can use all modules from django project, say the following piece of commands from the shell command:

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

now当我尝试将所有命令收集到一个python脚本中时,说mytest.py,我无法执行脚本。我必须错过一些重要的东西。

now, when I tried to collect all my commands into a python script, say "mytest.py", I cannot execute the script. I must missed something important.

我发出了python mytest.py

I issued python mytest.py

然后我得到了导入错误:无法导入设置是否在sys路径上?

then I got Import error: could not import settings Is it on sys path?"

我位于settings.py所在的项目目录中。

I'm in the project directory where settings.py resides.....

有些人可以帮助我吗?

谢谢。

推荐答案

尝试使用 Django管理命令

# 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

然后(如果您遵循文档),您将能够以下列方式执行命令:

And then (if you follow the docs) you will be able to execute the command in the following fashion:

python manage.py my_command

这篇关于使用django:from“python manage.py shell”到python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆