
在c++中实现一个日志记录器,并通过pybind11暴露给python使用时,一个常见的需求是记录日志消息的来源,即python脚本的文件名和调用日志函数的具体行号。例如,当python脚本中的logger.debug("debug message")被调用时,我们希望c++日志系统能够捕获到script.py:2这样的信息。
Python标准库中的 inspect 模块提供了强大的功能来检查活动对象、模块、类或函数。我们可以利用 inspect.stack() 函数来获取当前的调用栈信息。
inspect.stack() 返回一个包含帧信息对象的列表。每个帧信息对象都包含了关于调用栈中特定帧的详细信息,包括文件名、行号、函数名等。对于我们的需求,我们通常关心的是紧邻C++函数调用的Python帧,它通常是列表中的第一个元素。
以下是一个将上述逻辑整合到Pybind11绑定函数的示例:
#include <chrono>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <memory> // For std::shared_ptr
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
namespace py = pybind11;
// 定义一个简单的日志类
class PythonLogger {
public:
    PythonLogger(const std::string& filename) {
        // 实际应用中会打开并写入文件
        std::cout << "Logger initialized for file: " << filename << std::endl;
    }
    void log(const std::string& msg) {
        // 1. 导入 inspect 模块
        py::module inspect_mod = py::module::import("inspect");
        // 2. 获取调用栈
        py::list frames = inspect_mod.attr("stack")();
        // 3. 提取调用帧 (通常是第一个)
        py::object calling_frame = frames[0]; // 注意:这里的索引可能需要根据实际调用深度调整
                                            // 对于直接从Python调用C++函数,通常是0或1。
                                            // 实际测试中,如果是直接调用,0是C++内部帧,1是Python调用帧。
                                            // 鉴于原始问题中的frames[0]可用,我们在此沿用。
                                            // 如果出现错误,请尝试 frames[1]
        // 4. 获取文件名和行号
        py::str filename_py = calling_frame.attr("filename");
        py::int_ line_no_py = calling_frame.attr("lineno");
        // 5. 类型转换
        auto const filename = filename_py.cast<std::string>();
        auto const line_no = line_no_py.cast<uint32_t>();
        // 生成带时间戳的日志信息
        using std::chrono::system_clock;
        auto const timestamp = system_clock::to_time_t(system_clock::now());
        std::cout << "["
                  << std::put_time(std::localtime(×tamp), "%FT%T%z")
                  << "] [" << filename << ":" << line_no << "]: "
                  << msg << "\n";
    }
};
// Pybind11 绑定
PYBIND11_EMBEDDED_MODULE(pylogger_module, m) {
    py::class_<PythonLogger, std::shared_ptr<PythonLogger>>(m, "Logger")
        .def(py::init<const std::string&>())
        .def("debug", &PythonLogger::log, "Logs a debug message.");
}
int main() {
    // 初始化并管理Python解释器生命周期
    py::scoped_interpreter guard{};
    try {
        // 创建C++ Logger实例
        auto logger = std::make_shared<PythonLogger>("application.log");
        // 将C++ Logger实例注入到Python全局命名空间
        py::module_::import("pylogger_module"); // 确保模块被导入
        py::globals()["logger"] = logger;
        // 执行Python脚本内容
        py::exec(R"(
import pylogger_module
def func_a():
    logger.debug("Message from func_a.")
def func_b():
    func_a()
    logger.debug("Message from func_b.")
# 直接调用
logger.debug("Direct call from script.")
func_a()
func_b()
)");
    } catch (py::error_already_set& e) {
        std::cerr << "Python error: " << e.what() << "\n";
    }
    return 0;
}运行上述C++代码,将得到类似以下输出(行号会根据实际代码调整):
立即学习“Python免费学习笔记(深入)”;
Logger initialized for file: application.log [2023-10-27T10:30:00+0800] [<string>:13]: Direct call from script. [2023-10-27T10:30:00+0800] [<string>:6]: Message from func_a. [2023-10-27T10:30:00+0800] [<string>:7]: Message from func_a. [2023-10-27T10:30:00+0800] [<string>:10]: Message from func_b.
注意:在Pybind11绑定函数中,inspect.stack()[0]可能指向C++内部的包装帧。通常,Python调用帧会是inspect.stack()[1]或更深。在上述示例中,由于是通过py::exec执行的字符串,frames[0]指向了执行字符串的帧。如果Python脚本是一个单独的文件,并且直接调用C++绑定函数,则frames[0]通常指向该Python脚本的调用行。建议在实际开发中进行测试以确定正确的索引。
sys._getframe 是Python sys 模块中的一个非公开(以下划线开头)函数,它允许直接访问当前调用栈中的帧对象。相比 inspect.stack(),它可能具有更低的开销,因为它不需要构建完整的帧信息对象列表。
sys._getframe(n) 返回当前调用栈中指定层级的帧对象。n=0 表示当前帧,n=1 表示调用当前帧的帧,依此类推。一旦获取到帧对象,我们可以通过其 f_code 属性(代码对象)获取 co_filename(文件名),以及直接通过 f_lineno 属性获取行号。
修改 PythonLogger::log 方法,使用 sys._getframe:
// ... (其他头文件和PythonLogger类定义保持不变) ...
void PythonLogger::log(const std::string& msg) {
    // 1. 导入 sys 模块
    py::module sys_mod = py::module::import("sys");
    // 2. 获取调用帧 (通常是0或1,取决于C++函数的调用深度)
    // 经验证,对于直接从Python脚本调用C++绑定函数,_getframe(0)指向Python调用帧
    py::object calling_frame = sys_mod.attr("_getframe")(0); 
    // 3. 获取文件名和行号
    py::str filename_py = calling_frame.attr("f_code").attr("co_filename");
    py::int_ line_no_py = calling_frame.attr("f_lineno");
    // 4. 类型转换
    auto const filename = filename_py.cast<std::string>();
    auto const line_no = line_no_py.cast<uint32_t>();
    // 生成带时间戳的日志信息
    using std::chrono::system_clock;
    auto const timestamp = system_clock::to_time_t(system_clock::now());
    std::cout << "["
              << std::put_time(std::localtime(×tamp), "%FT%T%z")
              << "] [" << filename << ":" << line_no << "]: "
              << msg << "\n";
}
// ... (Pybind11绑定和main函数保持不变) ...运行使用 sys._getframe 的代码,将得到与 inspect.stack() 类似的结果。
开销: 无论是 inspect.stack() 还是 sys._getframe(),每次调用都会涉及Python解释器内部的帧检查,这会带来一定的性能开销。在高性能或高频率调用的场景下,这可能是一个值得关注的瓶颈。sys._getframe 通常被认为比 inspect.stack() 效率更高,因为它避免了构建完整的帧列表。
缓存: 为了减少重复查找模块和属性的开销,可以将 inspect.stack 函数对象或 sys._getframe 函数对象缓存起来。例如:
// 在 PythonLogger 类的构造函数中缓存
class PythonLogger {
public:
    PythonLogger(const std::string& filename) : 
        getframe_fn(py::module::import("sys").attr("_getframe")) {
        std::cout << "Logger initialized for file: " << filename << std::endl;
    }
    void log(const std::string& msg) {
        py::object calling_frame = getframe_fn(0); // 直接使用缓存的函数对象
        // ... (其余逻辑不变) ...
    }
private:
    py::object getframe_fn; // 缓存 _getframe 函数
};注意事项: 缓存Python对象时,必须确保其生命周期不超过Python解释器的生命周期。在 py::scoped_interpreter 的上下文中使用类成员变量缓存通常是安全的,因为解释器在所有对象被销毁后才关闭。
Python C API: 对于极致性能的场景,可以考虑直接使用Python C API来操作帧对象(PyFrameObject)和代码对象(PyCodeObject)。然而,这通常涉及更复杂的代码,并且可能依赖于Python解释器的内部实现细节,这些细节在不同版本之间可能发生变化,导致代码维护成本增加。除非有非常严格的性能要求,否则不建议优先选择此方法。
在Pybind11项目中从C++获取Python调用者的文件名和行号,主要有两种实用方法:
两种方法都需要将Python对象转换为C++类型。在实际应用中,建议根据项目的性能需求和对Python内部函数稳定性的接受程度选择合适的方法,并考虑通过缓存来优化性能。
以上就是使用Pybind11从Python获取C++函数调用位置的行号的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号