首页 > 解决方案 > Python:在 CI/CD 过程中出现 TypeError

问题描述

我尝试将 TXT 文件添加到我的 python 包中,通过 加载它pkg_resources,然后用数据做一些其他的事情。我的python包的结构如下:

package_name
  |-- requirements.txt
  |-- setup.py
  |-- MANIFEST.in
  |-- package
    |-- __init__.py
    |-- name
      |-- __init__.py
      |-- my_file.py
      |-- test
        |-- __init__.py
        |-- test_1.py
      |-- data
        |-- MY_DATA.txt

的内容~/package_name/package/name/my_file.py

import pkg_resources

DATA_PATH = 'package.name.data'
MY_DATA_PATH = pkg_resources.resource_filename(DATA_PATH, 'MY_DATA.txt')


def do_some_stuff_with_data(data_path=MY_DATA_PATH):
    ...

当我在本地机器上运行测试时,代码运行没有任何问题。git但是,当我尝试通过 CI/CD将其推送到存储库时,测试会因以下错误而失败:

/tmp/testenv/lib/python3.7/site-packages/package/name/test/test_name.py:13: in <module>
    from package.name.my_file import (
/tmp/testenv/lib/python3.7/site-packages/package/name/my_file.py:28: in <module>
    MY_DATA_PATH = pkg_resources.resource_filename(DATA_PATH, 'MY_DATA.txt')
/tmp/testenv/lib/python3.7/site-packages/pkg_resources/__init__.py:1206: in resource_filename
    return get_provider(package_or_requirement).get_resource_filename(
/tmp/testenv/lib/python3.7/site-packages/pkg_resources/__init__.py:437: in get_provider
    return _find_adapter(_provider_factories, loader)(module)
/tmp/testenv/lib/python3.7/site-packages/pkg_resources/__init__.py:1452: in __init__
    self.module_path = os.path.dirname(getattr(module, '__file__', ''))
/tmp/testenv/lib/python3.7/posixpath.py:156: in dirname
    p = os.fspath(p)
E   TypeError: expected str, bytes or os.PathLike object, not NoneType

我知道,该数据路径已正确写入。我检查了几次错别字。我还认为该错误可能是由于未向MANIFEST.in文件添加数据路径引起的。但是,添加并没有解决问题。

你知道我错过了什么吗?

标签: python-3.xgitcontinuous-integrationpackagepytest

解决方案


如果有人遇到同样的问题,我已经通过将__init__.py文件添加到~/package_name/package/name/data/文件夹中解决了这个问题。


推荐阅读