如何在Python项目中正确组织文件

时间:2012-02-14 11:38:03

标签: python

我在使用Python项目时遇到了一些困难。这是参考Qn 48Learn Python the Hard Way

导致问题的测试人员lexicon_tests.py的行:

from ex48 import lexicon

我看到的错误是:

ImportError: no module named ex48

我想知道这是因为我没有在projects文件夹中正确组织我的文件:我有一个名为ex48的文件夹,其子文件夹包括testslexicon。在lexicon中,我有lexicon.py文件。在tests中,我有lexicon_tests.py

文件

上述组织是否有错误?

编辑:在此处发布代码 -

在/ ex48中,我有setup.py

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
    'description': 'My Project',
    'author': 'MyName',
    'url': 'URL to get it at.',
    'download_url': 'Where to download it.',
    'author_email': 'My email.',
    'version': '0.1',
    'install_requires': ['nose'],
    'packages': ['ex48'],
    'scripts': [],
    'name': 'projectname'
}

setup(**config)

在/ ex48 / lexicon中,我有lexicon.py

class lexicon:
    @staticmethod

    def scan(string):   

        direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left',          'right', 'back']
        verbs = ['go','stop','kill','eat']
        stop = ['the','in', 'of', 'from', 'at','it']
        nouns = ['door', 'bear', 'princess', 'cabinet']

        words = string.split()

        result = []
        for word in words:
                if word in direction:
                result.append(('direction',word))

等等。 。 。最后有return result。已正确添加所有环境变量。我看到的错误是ImportError,其名称为lexicon。

4 个答案:

答案 0 :(得分:2)

检查ex48文件夹中是否存在 __init__.py 文件。它需要创建一个包,可以是空的。

答案 1 :(得分:1)

该错误表明ex48不在您的python导入搜索路径中。您可以通过执行以下操作来检查:

    import sys
    sys.path

修改

以下是向python的导入搜索路径添加路径的分步教程:Set up Windows Python Path system environment variable。我猜你没有正确地添加它们,如果它们仍然没有出现在sys.path中,并且直到他们确实没有理由这样做。

修改

现在出现新错误。当您执行from ex48 import lexicon时,其中一个应该是真的,以使其起作用:

  1. 文件夹lexicon中存在名为ex48的文件夹, ex48lexicon都有__init__.py }

  2. lexicon.py直接位于ex48__init__.py位于ex48

  3. 修改

    你说你从上次评论中得到的错误是由不良身份引起的。您在上面发布的代码需要def scan(string):

    以下每行的额外标识级别

答案 2 :(得分:1)

对于此

from ex48 import lexicon
result = lexicon.scan("north south east")

要工作,您应该将lexicon.py放在文件夹ex48中,lexicon.py应该在模块级别包含scan函数,而不是类方法。

使用当前代码,您在包lexicon的模块lexicon中有一个类lexicon,导入语句必须看起来像

from ex48.lexicon.lexicon import lexicon

答案 3 :(得分:0)

实际上,在你的ex48项目中,你会看到有一个setup.py文件。在那里,你会看到这一行:

'packages': ['NAME'],

您要做的是将NAME更改为您的文件夹名称(ex48),所以它看起来像这样:

'packages': ['ex48'],

确保在ex48文件夹中,您具有已定义扫描功能的lexicon.py。不需要新的课程。

经过编辑后,nosetests应该正确运行:

from ex48 import lexicon