简体   繁体   中英

Can't import local module inside script, like I do in Django shell

This is the error:

Traceback (most recent call last):
File "twitterstream.py", line 3, in <module>
from tweemo.models import TwitterStream
ImportError: No module named tweemo.models

Background:

In Django I have a simple model which looks like so:

from django.db import models

class TwitterStream(models.Model):
   text = models.CharField()

From inside the Django shell I can do the following without problems

>>> from tweemo.models import TwitterStream
>>> tweet = TwitterStream.objects.create(text = 'hello again')
>>> tweet.text
'hello again'

Because this worked in the django shell, I thought I could insert this line:

>>> from tweemo.models import TwitterStream

into any regular python script and, for example, insert the data into the TwitterStream Model (and thus my into my Mondo Database) form within the script.

Basically, I have a script which does print out the twitter live stream onto the command line. Itried to modify it by including this

 >>> from tweemo.models import TwitterStream

and changing this:

for line in response:
    print response

into this:

for line in response:
    tweet = str(tweet) + str(" ") + str(count) 
    tweet = TwitterStream.objects.create(text = line.strip())
    count += 1

FYI: My models.py containing the TwitterStream class is inside my app 'tweemo' which is inside a project, also called 'twitter'. The python script I want to send the live stream into mymongo DB with, is in the same folder as the models.py file -the tweemo app folder.

在此处输入图片说明

I'm new to Django/Mongo so Imight be way off here..

Thanks in advance

Python will automatically check for modules in the same directory as the input script, so you can just write

from models import TwitterStream

This behaviour is different when you are in the django shell, as django appends the project root path to sys.path , which Python also uses when searching for modules .

if importing of model works via django shell it has to work via py files within project folder. My only guess would be to delete pyc file in project folder and test.If not, @dannymilsom solution will come in handy :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM