[英]Running a python commands from a python script in a python (Django) shell. Django
I'm working with Django and I'd created two database. 我正在使用Django,并创建了两个数据库。 Everything seems to work fine, but then I had to edit one of the two and add a column.. From that moment the db wouldn't work anymore, so I exported in a text file the first database and thinking "now I recreate the two db and run a python script to refill the first one".
一切似乎都可以正常工作,但是然后我不得不编辑两者之一并添加一列。.从那一刻起,数据库就不再工作了,所以我在文本文件中导出了第一个数据库,并想“现在我重新创建了两个db并运行python脚本以填充第一个”。 The problem is that whene I try to run the script I get errors, because I can't run the command like bash using os.system, and I don't really know any other way... So, here's my code:
问题在于,当我尝试运行脚本时会出错,因为我无法使用os.system运行bash之类的命令,而且我真的不知道其他任何方式。因此,这是我的代码:
import os
def func ():
try:
FILE=open ("./languagedb.txt", "r")
except IOError:
print 'Can\'t open db file'
exit (1)
for line in FILE:
if (line.startswith('INSERT')):
values=line[43:-1]
language=values[1:3]
values=values[6:]
field=""
fieldBool=True
i=0
while fieldBool:
try:
c=values[i]
except:
print ''
if c != '\'':
field=field+str(c)
i=i+1
else:
fieldBool=False
values=values [(i+3):]
text=""
textBool=True
i=0
while textBool:
try:
c=values[i]
except:
print ''
if c != '\'':
text=text+str(c)
i=i+1
else:
textBool=False
comand="Language.objects.create(language=\""+language+"\", text=\""+text+"\", campo=\""+field+"\")"
os.system(comand)
This is the way I call the shell: 这就是我调用shell的方式:
python manage.py shell
and the commands I give it: 以及我给它的命令:
import django
from languageMods.models import *
import mymigration #The name fo the file containing the above code
mymigration.func()
And I get the following error, for example 我得到以下错误,例如
sh: -c: line 0: syntax error near unexpected token `language="en",'
Which is shell's error. 这是壳牌的错误。 Does someone know how to execute a command from a python script in a python shell?
有人知道如何从python shell中的python脚本执行命令吗?
如果按照描述方式启动脚本,则可以直接在代码中直接调用django DB API:
Language.objects.create(language=language, text=text, campo=field)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.