我如何获得当前的“包装”名称? (setup.py)

问题描述 投票:0回答:1

如何获取当前最顶层的软件包,即setup.py中定义的名称?

这里是我的tree

.
|-- README.md
|-- the_project_name_for_this_pkg
|   |-- __init__.py
|   |-- __main__.py
|   |-- _config
|   |   `-- foo.conf
|   |-- _data
|   |   `-- logging.yml
|   `-- tests
|       |-- __init__.py
|       `-- test_foo.py   <--- # executing from here
|-- requirements.txt
`-- setup.py

4 directories, 9 files

到目前为止,我唯一可以使用的解决方案是:

import os
import sys


os.path.basename(sys.path[1])

但是这显然是一个不好的解决方案。其他解决方案,例如在我的最高__name__文件中包含__init__.py并使用ast.parse读取ast.parse的相关部分,也似乎很麻烦。

我尝试过的其他解决方案-通过在setup.py python [sub]程序包中继承unittest.TestCaseunittest.TestCase中调用它们-包括检查classtestssys.modules[__name__],以及这些问题的答案:

BTW:万一您想知道为什么我想要软件包名称…是这样,所以我可以运行以下内容:

Get fully qualified class name of an object in Python
python setuptools pythonpath python-packaging pkg-resources
1个回答
1
投票

不完全确定更大的目标是什么,但也许您可能对阅读How can I access the current executing module or class name in Python?Get full caller name (package.module.function) (Python recipe)感兴趣。

类似于以下内容:

https://docs.python.org/2/library/modulefinder.html

并且更一般而言,从代码中检测项目名称(import pkg_resources version = pkg_resources.require('the_project_name_for_this_pkg')[0].version data_file = path.join(resource_filename('the_project_name_for_this_pkg', '__init__.py'), '_config', 'data_file.txt') )几乎是不可能的(或不值得做的工作)。对其进行硬编码会更容易。

© www.soinside.com 2019 - 2024. All rights reserved.