如何在python中打印内置模块的源代码?

MAS*_*MAN -1 python python-module ipython

我想打印一个内置方法的源代码。例如,数学是python的内置模块,我想打印ceil的源代码

我知道如何使用inspect.getsource打印自定义模块的源代码

需要帮助
我正在尝试创建一个程序,我可以在其中调用任何内置方法或函数,并且它将仅显示该函数或模块的源代码。
Python 几乎拥有内置库中的所有内容,我想使用这些库

示例:

input: factorial
output:
        def factorial(n):
            if n == 0:        
                return 1      
            else:      
                return n * factorial(n-1)
Run Code Online (Sandbox Code Playgroud)
工作得很好
import inspect
inspect.getsource(factorial)
Run Code Online (Sandbox Code Playgroud) 不起作用......导致类型错误
import inspect
import math
print(inspect.getsource(math.ceil)
Run Code Online (Sandbox Code Playgroud)
TypeError: <built-in function ceil> is not a module, class, method, function, traceback, frame, or code object
Run Code Online (Sandbox Code Playgroud)

提前致谢 :)

Pau*_*ine 6

如果源是 Python,你可以这样做:

import inspect
import math

try:
    print(inspect.getsource(math))
except OSError:
    print("Source not available, possibly a C module.")
Run Code Online (Sandbox Code Playgroud)

正如其他人已经评论过的那样,许多内置模块都是 C。如果是这种情况,您将不得不深入研究源代码 - 幸运的是,它并不难找到,结构非常直观。

对于 math.ceil,源代码位于 cpython 中 Modules/mathmodule.c 的第 1073 行

/*[clinic input]
math.ceil
    x as number: object
    /
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
[clinic start generated code]*/

static PyObject *
math_ceil(PyObject *module, PyObject *number)
/*[clinic end generated code: output=6c3b8a78bc201c67 
input=2725352806399cab]*/
{
    _Py_IDENTIFIER(__ceil__);
    PyObject *method, *result;

    method = _PyObject_LookupSpecial(number, &PyId___ceil__);
    if (method == NULL) {
        if (PyErr_Occurred())
            return NULL;
        return math_1_to_int(number, ceil, 0);
    }
    result = _PyObject_CallNoArg(method);
    Py_DECREF(method);
    return result;
}
Run Code Online (Sandbox Code Playgroud)