Python导入模块导致NameError

时间:2010-10-21 21:34:43

标签: python django module import nameerror

我遇到了模块导入问题。

在ubuntu 10.10上使用python 2.6

我有一个类,它将守护进程子类化为http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/。我创建了一个python包,其中包含一个代码,该代码可以从django项目中导入一些模型。代码在从类中使用时起作用,而不是对守护程序进行子类化。结构看起来像:

my_module
    __init__.py
   - bin
   - cfg
   - core
     __init__.py
     collection.py
     daemon.py

ItemRepository代码:

class ItemRepository(object):
    """This class provides an implementation to retrieve configuration data 
    from the monocle database
    """
    def __init__(self, project_path):
        if project_path is not None:
            sys.path.append(project_path)

        try:
            from django.core.management import setup_environ
            from someproj import settings
            setup_environ(settings)
            from someproj.someapp.models import ItemConfiguration
        except ImportError:
            print "Could not import models from web app.  Please ensure the\
            PYTHONPATH is configured properly"

    def get_scheduled_collectors(self):
        """This method finds and returns all ItemConfiguration objects 
        that are scheduled to run
        """
        logging.info('At the error path: %s' % sys.path)
        # query ItemConfigs from database
        items = ItemConfiguration.objects.filter(disabled=False) #ERROR OCCURS AT THIS LINE
        return [item for item in items if item.scheduled]

守护程序代码(在/usr/local/bin/testdaemon.py中):

import sys
from my_module.core.daemon import Daemon
from my_module.core.collection import ItemRepository
import logging
import time

class TestDaemon(Daemon):
    default_conf = '/etc/echodaemon.conf'
    section = 'echo'

    def run(self):
        while True:
            logging.info('The echo daemon says hello')
            ir = ItemRepository(project_path=self.project_path)
            items = ir.get_scheduled_collectors() #TRIGGERS ERROR
            logging.info('there are %d scheduled items' % len(items))
            time.sleep(1)

if __name__ == '__main__':
    TestDaemon().main()

我得到的错误是“NameError:全局名称'my_module'未定义”它已经过了导入但在尝试调用对象上的方法时失败了。我假设它与sys.path / PYTHONPATH有关,但我知道我的django项目正在路径上,因为我已将其打印出来。到目前为止,python文档或学习Python中的任何内容都没有帮助。有没有人有任何见解或知道对模块导入的良好参考?

更新:

现在我试图简化问题以使其更容易理解。现在我的目录结构如下:

/home
  /username
    /django
      /someproj
         /web
           models.py
      /my_module
         daemon.py

我已将/etc/bash.bashrc中的$ PYTHONPATH变量设置为'/ home / username / django'。

在testdaemon.py文件中,导入类似于:

import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration

但现在我得到一个ImportError:没有名为'someproj'的模块。所以我添加了路径。

import sys
sys.path.append('/home/username/django')
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration

现在ImportError说:没有名为'web'的模块。这是追溯:

Traceback (most recent call last):
  File "testdaemon.py", line 77, in <module>
    TestDaemon('/tmp/testdaemon.pid').run()
  File "testdaemon.py", line 47, in run
    scheduled_items = [item for item in ItemConfiguration.objects.filter(disabled=False) if collector.scheduled]
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 141, in filter
    return self.get_query_set().filter(*args, **kwargs)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 550, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 568, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1128, in add_q
    can_reuse=used_aliases)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1026, in add_filter
    negate=negate, process_extras=process_extras)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1179, in setup_joins
    field, model, direct, m2m = opts.get_field_by_name(name)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 291, in get_field_by_name
    cache = self.init_name_map()
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 321, in init_name_map
    for f, model in self.get_all_related_m2m_objects_with_model():
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 396, in get_all_related_m2m_objects_with_model
    cache = self._fill_related_many_to_many_cache()
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 410, in _fill_related_many_to_many_cache
    for klass in get_models():
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 167, in get_models
    self._populate()
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 61, in _populate
    self.load_app(app_name, True)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 76, in load_app
    app_module = import_module(app_name)
  File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named web

从我之前的评论开始,我尝试添加:

import sys
sys.path.append('/home/username/django')
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj import web
from someproj.web import models
from someproj.web.models import ItemConfiguration

但这没有帮助。所以我创建了一个非常简单的文件:

#!/usr/bin/python

import logging
import time
import sys
sys.path.append('/home/username/django')
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration

if __name__ == '__main__':    
    print sys.path
    items = ItemConfiguration.objects.all()
    for item in items:
        print item

这有效!这真的只会让我感到困惑。所以现在我想也许它与守护进程有关。它使用os.fork(),我不确定路径是否仍然设置。这就是我在/etc/bash.bashrc文件中设置$ PYTHONPATH变量的原因。

更多见解?我真的需要守护进程,因为我需要一个长时间运行的过程,所以没有多少选择。

3 个答案:

答案 0 :(得分:0)

使用from my_module.core.daemon import Daemon,您实际上并未将加载的模块my_module绑定到变量。使用import my_module 就在您进行其他进口之前或之后。

在代码中解释:

>>> from xml import dom
>>> xml
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xml' is not defined
>>> import xml
>>> xml
<module 'xml' from '/usr/lib/python2.6/xml/__init__.pyc'>

答案 1 :(得分:0)

你让我困惑你的意思是“你的Django项目”是你的模块“my_module”是更高版本的一部分吗?像这样的东西

django_project
    |
    |my_module
        __init__.py
        - bin
        - cfg
        - core
           __init__.py
           collection.py
           daemon.py

如果是这样,如果你说django_project在PYTHONPATH中,那么你应该像这样导入my_module:

from django_project.my_module.core.daemon import Daemon

顺便说一下,最好导入模块,没有类这样的功能都不是这样的:

from django_project.my_module.core import daemon

并像这样使用它:

daemon.Daemon()

答案 2 :(得分:0)

最后我需要在INSTALLED_APPS设置的Django项目的settings.py文件中引用我的应用程序的完全限定名称。 “someproj.web”而不仅仅是“web”。使用较短的版本在Django项目中运行良好,从外面看不太好。