解析python文件时出现令人烦恼的Ctrl+M问题

Annoying Ctrl+M issue parsing python files

本文关键字:烦恼 Ctrl+M 问题 python 文件 解析      更新时间:2023-10-16

在C++中嵌入的boost python中,我让C++解析一个包含一个简单函数的python(通过boost python)文件,该文件反过来调用C++方法来完成某个实现。虽然这些看起来很荒谬,但我们选择这样做是为了日志记录的优势和python提供的其他灵活性。

我注意到,在Linux上,如果包含要实现的函数的python文件是在Windows中编辑的,因此每行末尾都有令人讨厌的回车符(^M),那么boost python将无法解析它,并出现语法错误。当然,运行dos2unix从python文件中剥离^M字符可以解决这个问题。如果有帮助的话,我在C++中调用boost python的片段如下:

bool exec_command(const std::string& cmd, ...) {
...
...
    try {
        boost::python::object main = boost::python::import("__main__");
        boost::python::object global(main.attr("__dict__"));
        if( !context.empty() ) {
            boost::python::exec(
                "import _project",
                global,
                global
            );
            for(smart_handle_context::const_iterator itr = handle_context.begin(); itr != hndle_context.end(); ++itr) {
                global[itr->first] = boost::python::object(itr->second);    
            }
        }
        boost::python::exec(
            cmd.c_str(),
            global,
            global
        );
    } 
    catch( boost::python::error_already_set& ) {
        PyErr_Print();
        return false;
    }
    return true;
}

在上面的代码段中,smart_handle_context是std::strings到特定于实现的智能句柄的映射的typedef。我还注意到,在Linux中,直接在具有^M字符的文件上运行python不会给它的解析器带来问题。任何关于如何在不必运行dos2unix解决方法的情况下绕过^M问题的想法(希望在代码中进行修复)都将受到赞赏。谢谢

您可以定义一个从字符串中删除0x0D字符的函数,类似于:

#include <algorithm>
std::string removeWindowsLineEndings(std::string s)
{
    s.erase(std::remove(s.begin(), s.end(), 'x0D'), s.end());
    return s;
}