1

我遇到了模块导入问题。

在 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 文档或 Learning 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 变量的原因。

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

4

3 回答 3

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'>
于 2010-10-21T21:42:27.773 回答
0

最终我需要在 INSTALLED_APPS 设置中的 Django 项目的 settings.py 文件中引用我的应用程序的完全限定名称。“someproj.web” 而不仅仅是“web”。在 Django 项目中使用较短的版本可以正常工作,只是从外部看不太好。

于 2010-11-08T19:36:47.470 回答
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()
于 2010-10-21T22:01:17.557 回答