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的许多元信息功能的非常好的概述:
#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的许多元信息功能的非常好的概述:
#3
#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块中,并根据您的情况处理异常。 (另外,正如我可能希望的那样,你需要在你想要调用检查功能的模块中导入检查)。