如何获取当前最顶层的软件包,即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.TestCase
的unittest.TestCase
中调用它们-包括检查class
,tests
和sys.modules[__name__]
,以及这些问题的答案:
inspect.getmodule
inspect.getmodule
inspect.stack
inspect.stack
BTW:万一您想知道为什么我想要软件包名称…是这样,所以我可以运行以下内容:
Get fully qualified class name of an object in Python
不完全确定更大的目标是什么,但也许您可能对阅读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')
)几乎是不可能的(或不值得做的工作)。对其进行硬编码会更容易。