如何获取当前运行的模块路径/名称 [英] How to get the current running module path/name

查看:30
本文介绍了如何获取当前运行的模块路径/名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过了,这似乎是一个没有简单答案的简单问题.

I've searched and this seems to be a simple question without a simple answer.

我有一个文件 a/b/c.py,它将用 python -m a.b.c 调用.我想获取模块级别的值 a.b.c.

I have the file a/b/c.py which would be called with python -m a.b.c. I would like to obtain the value a.b.c in the module level.


USAGE = u'''\
Usage:
    python -m %s -h
''' % (what_do_i_put_here,)

因此,当我收到 -h 选项时,我会显示 USAGE 而无需实际写下每个脚本中的实际值.

So when I receive the -h option, I display the USAGE without the need to actually write down the actual value in each and every script.

我真的需要经过inspect才能得到想要的值吗?

Do I really need to go through inspect to get the desired value?

谢谢.

如前所述,有答案(我已经搜索过),但不是简单的答案.要么使用 inspect,使用 traceback,要么操作 __file____package__ 并做一些子串来得到答案.但没有什么比我在模块中有一个类那么简单,我可以只使用 myClass.__module__ 并且我会得到我想要的答案.__name__ 的使用(不幸的是)没用,因为它总是 __main__.

As said, there are answers (I've searched), but not simple answers. Either use inspect, use of traceback, or manipulate __file__ and __package__ and do some substring to get the answer. But nothing as simple as if I had a class in the module, I could just use myClass.__module__ and I would get the answer I want. The use of __name__ is (unfortunately) useless as it's always __main__.

另外,这是在 python 2.6 中,我不能使用任何其他版本.

Also, this is in python 2.6 and I cannot use any other versions.

推荐答案

这对我有用:

__loader__.fullname

此外,如果我从 a\ 执行 python -m b.c,我会按预期得到 'b.c'.

Also if I do python -m b.c from a\ I get 'b.c' as expected.

不完全确定 __loader__ 属性是什么,所以如果这不好,请告诉我.

Not entirely sure what the __loader__ attribute is so let me know if this is no good.

编辑:它来自 PEP 302:http://www.python.org/dev/peps/pep-0302/

edit: It comes from PEP 302: http://www.python.org/dev/peps/pep-0302/

来自链接的有趣片段:

load_module() 方法有一些它必须的职责在它运行任何代码之前完成:

The load_module() method has a few responsibilities that it must fulfill before it runs any code:

...

  • 它应该向模块添加一个 __loader__ 属性,设置为装载机对象.这主要用于内省,但可以使用对于特定于进口商的附加功能,例如获取关联的数据与进口商合作.

所以看起来它应该在所有情况下都能正常工作.

So it looks like it should work fine in all cases.

这篇关于如何获取当前运行的模块路径/名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆