【问题标题】:Avoid to import the path when using subfolders in python在python中使用子文件夹时避免导入路径
【发布时间】:2018-01-19 14:15:54
【问题描述】:

以前我在没有单元测试的情况下工作,我的项目有这样的结构:

-main.py
   -folderFunctions:
       -functionA.py

只使用folderFunctions中的init文件,然后导入

 from folderFunctions import functionA

一切正常。

现在我也有以这种方式组织的单元测试:

-main.py
-folderFunctions:
    -functionA.py
    -folderTest:
       -testFunctionA.py

所以我必须在 functionA.py 和 testFunctionA.py 中添加(为了运行 testFunctionA.py)这两行来导入路径:

 myPath = os.path.dirname(os.path.abspath(__file__))
 sys.path.insert(0, myPath + '../..') 

通过这种方式,测试可以正常工作。 但这对我来说很丑,我想也不是很pythonic。 有没有办法让它更优雅?

【问题讨论】:

  • main.py 所在的同一级别上创建一个名为 tests 的文件夹,并将所有测试放在其中。
  • @orangelnk 我读到通常测试文件夹与功能处于同一级别或更深层次。主要级别仍然是pythonic吗?
  • 我不得不承认,在包装方面我远非专家,但 99% 的情况下,当我查看一个包裹时,我会看到与 @ 相同级别的 tests 文件夹987654328@ 位于(意味着比所有实际代码高 1 级)。

标签: python testing path directory subdirectory


【解决方案1】:

如果您希望您的库/应用程序变得更大且易于打包,我几乎不建议将源代码与测试代码分开,因为不应将测试代码打包在二进制发行版(egg 或 wheel)中。

你可以遵循这个树形结构:

+-- src/
|    +-- main.py
|    \-- folder_functions/  # <- Python package
|        +-- __init__.py
|        \-- function_a.py
\-- tests/
    \-- folder_functions/
        +-- __init__.py
        \-- test_function_a.py

注意:根据PEP8,Python 包和模块名称应为“蛇形”(小写+下划线)。

如果你有(而且你应该)一个主包,src 目录可以避免。

正如其他 cmets 中所述,setup.py 文件应位于 srctests 文件夹(根级别)旁边。

阅读Python Packaging User Guide

编辑

下一步是创建一个setup.py,例如:

from setuptools import find_packages
from setuptools import setup

setup(
    name='Your-App',
    version='0.1.0',
    author='Your Name',
    author_email='your@email',
    url='URL of your project home page',
    description="one line description",
    long_description='long description ',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Python Software Foundation License',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Programming Language :: Python',
        'Topic :: Software Development',
    ],
    platforms=["Linux", "Windows", "OS X"],
    license="MIT License",
    keywords="keywords",
    packages=find_packages("src"),
    package_dir={'': 'src'},
    entry_points={
        'console_scripts': [
            'cmd_name = main:main',
        ],
    })

配置项目后,您可以创建一个 virtualenv 并在其中安装您的应用程序:

virtualenv your-app
source your-app/bin/activate
pip install -e .

您可以使用 unitests 标准模块运行测试。

要在 test_function_a.py 中导入您的模块,请照常进行:

from folder_functions import function_a

【讨论】:

  • 感谢您的帮助!那么有了这个树形结构,我怎么能在 test_function_a.py function_a.py 中导入呢?
【解决方案2】:

更优雅的方法是from folderFunctions.folderTest import testFunctionA,并确保在folderTest 目录中有一个__init__.py 文件。你也可以看看这个question

【讨论】:

    猜你喜欢
    • 2016-09-29
    • 2013-07-12
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多