给定一个Python类,我如何在我的代码中检查并找到它所在的位置?

时间:2022-10-30 09:13:53

I'm building a debugging tool.

我正在构建一个调试工具。

IPython lets me do stuff like

IPython让我做的事情

MyCls??

And it will show me the source.

它会告诉我源头。

4 个解决方案

#1


8  

sys.modules[MyCls.__module__].__file__

or

inspect.getsourcefile(MyCls)

There are more __xxx__ attributes on various objects you might find useful.

您可能会发现有用的各种对象上有更多__xxx__属性。

#2


4  

Here's a pretty good overview of many of Python's meta-info capabilities:

以下是Python的许多元信息功能的非常好的概述:

http://www.ibm.com/developerworks/library/l-pyint.html

#3


2  

The inspect module has everything you need.

检查模块具备您需要的一切。

#4


2  

If you just want to see the source, inspect.getsource is a very direct way to do that; for more advanced uses (getting the source file, line numbers, etc), see other functions in inspect documented at the same URL just before getsource. Note that each such function will raise an exception if source is not available, so make sure to be within a try/except block when you call it, and handle the exception as appropriate for your case. (Also, as I might hope goes without saying, you do need to import inspect in your modules in which you want to call inspect functionality).

如果您只想查看源代码,inspect.getsource是一种非常直接的方法;对于更高级的用途(获取源文件,行号等),请参阅在getsource之前在相同URL处记录的inspect中的其他函数。请注意,如果source不可用,每个此类函数都将引发异常,因此请确保在调用它时位于try / except块中,并根据您的情况处理异常。 (另外,正如我可能希望的那样,你需要在你想要调用检查功能的模块中导入检查)。

#1


8  

sys.modules[MyCls.__module__].__file__

or

inspect.getsourcefile(MyCls)

There are more __xxx__ attributes on various objects you might find useful.

您可能会发现有用的各种对象上有更多__xxx__属性。

#2


4  

Here's a pretty good overview of many of Python's meta-info capabilities:

以下是Python的许多元信息功能的非常好的概述:

http://www.ibm.com/developerworks/library/l-pyint.html

#3


2  

The inspect module has everything you need.

检查模块具备您需要的一切。

#4


2  

If you just want to see the source, inspect.getsource is a very direct way to do that; for more advanced uses (getting the source file, line numbers, etc), see other functions in inspect documented at the same URL just before getsource. Note that each such function will raise an exception if source is not available, so make sure to be within a try/except block when you call it, and handle the exception as appropriate for your case. (Also, as I might hope goes without saying, you do need to import inspect in your modules in which you want to call inspect functionality).

如果您只想查看源代码,inspect.getsource是一种非常直接的方法;对于更高级的用途(获取源文件,行号等),请参阅在getsource之前在相同URL处记录的inspect中的其他函数。请注意,如果source不可用,每个此类函数都将引发异常,因此请确保在调用它时位于try / except块中,并根据您的情况处理异常。 (另外,正如我可能希望的那样,你需要在你想要调用检查功能的模块中导入检查)。