icosac
icosac

Reputation: 39

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

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:

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?

Upvotes: 0

Views: 191

Answers (1)

ger.s.brett
ger.s.brett

Reputation: 3308

If you start your script the way you describe it you can just call the django DB API directly in your code:

Language.objects.create(language=language, text=text, campo=field)

Upvotes: 1

Related Questions