我已经搜索过了,这似乎是一个没有简单答案的简单问题。
我有文件 a/b/c.py
可以用 python -m a.b.c
调用。我想在模块级别获取值a.b.c
。
USAGE = u'''\
Usage:
python -m %s -h
''' % (what_do_i_put_here,)
所以当我收到 -h
选项时,我会显示 USAGE
而无需在每个脚本中实际写下实际值。
我真的需要通过 inspect
来获得想要的值吗?
谢谢。
编辑: 如前所述,有答案(我已经搜索过),但不是简单的答案。要么使用inspect
,要么使用traceback
,或者操作__file__
和__package__
并做一些子字符串来得到答案。但没有什么比我在模块中有一个类更简单的了,我只需使用 myClass.__module__
就可以得到我想要的答案。 __name__
的使用(不幸的是)没有用,因为它总是 "__main__"
。
另外,这是在 python 2.6 中,我不能使用任何其他版本。
最佳答案
这对我有用:
__loader__.fullname
另外,如果我从 a\执行 python -m b.c,我会按预期得到 'b.c'。
不完全确定 __loader__ 属性是什么,如果不好请告诉我。
编辑:来自 PEP 302:http://www.python.org/dev/peps/pep-0302/
来自链接的有趣片段:
The load_module() method has a few responsibilities that it must fulfill before it runs any code:
...
- It should add an __loader__ attribute to the module, set to the loader object. This is mostly for introspection, but can be used for importer-specific extras, for example getting data associated with an importer.
所以看起来它应该在所有情况下都能正常工作。
关于python - 如何获取当前正在运行的模块路径/名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5183601/