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

如何在python中打印内置模块的源代码?,python,ipython,python-module,Python,Ipython,Python Module,我想打印一个内置方法的源代码。 例如,math是python的内置模块,我想打印ceil 我知道如何使用inspect.getsource打印自定义模块的源代码 需要帮助我正在尝试创建一个程序,在该程序中,我可以调用任何内置方法或函数,它将仅显示该函数或模块的源代码 Python几乎拥有内置库中的所有内容,我想使用这些库 示例: input: factorial output: def factorial(n): if n == 0:

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

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

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

示例:

input: factorial
output:
        def factorial(n):
            if n == 0:        
                return 1      
            else:      
                return n * factorial(n-1)

很好用
不起作用。。。导致类型错误
import inspect
import math
print(inspect.getsource(math.ceil)
TypeError:不是模块、类、方法、函数、回溯、帧或代码对象

提前感谢:)

如果源代码是Python,则可以执行以下操作:

import inspect
import math

try:
    print(inspect.getsource(math))
except OSError:
    print("Source not available, possibly a C module.")
正如其他人已经评论过的,许多内置模块都是C。如果是这种情况,你必须深入到源代码中——幸运的是,这并不难找到,它的结构非常直观

对于math.ceil,源代码位于cpython中的Modules/mathmodule.c的下面:

/*[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;
}

我认为这是不可能的。我认为大多数内置函数都是用python接口包装器编译的C函数。(如果您想“检查代码,您可以随时检查存储库”)在
ipython
中,您可以使用
函数查看源代码(如果是用Python编写的)。但如果从C代码编译,它将被标记为内置。通常我会在网上查找开发库(例如github),但是将Python函数名与C函数名进行匹配可能会很棘手。您真的需要查看源代码才能使用库吗?但是如上所述,如果您使用的是CPython,那么大多数hte内置库都是用C实现的,您将无法访问源代码。不过,你可以在github repo上找到它。在cpython github上,我在cpython/Modules/mathmodule.c中找到了一个
math.ceil
,看起来就是源代码。从下载c源代码,然后构建一个模块/源文件名表,或者编写
grep
的功能来搜索c源代码。
import inspect
import math

try:
    print(inspect.getsource(math))
except OSError:
    print("Source not available, possibly a C module.")
/*[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;
}