解析python文件时出现令人烦恼的Ctrl+M问题
Annoying Ctrl+M issue parsing python files
在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::string
s到特定于实现的智能句柄的映射的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;
}
相关文章:
- 热键/按钮,根据需要进行编译,但不运行(在F5和Ctrl+Shift+B之间)
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- Ctrl + 不适用于在 Visual Studio 中运行该程序
- 最烦人的解析甚至更令人烦恼
- C++键盘挂钩 CTRL 键卡住
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- 如果 I/O read() 处于阻塞阶段,如何使用 Ctrl+C 退出 C++ 程序?
- 如何让 getc(stdin) 返回 ctrl 字符?
- 在 ov5640 上使用 V4L2 设置 ctrl
- Ncurses CTRL + s hangs getch()
- C++CTRL+C处理程序有未定义的行为
- 如果输入缓冲区不为空,请使用getchar.()检测Ctrl+d
- Qt 键按事件处理程序仅在按下 ctrl、alt 或 shift 键时做出反应
- 我的控制台处理程序不处理 CTRL+C,即使设置正确
- 当用户在键盘上按住 CTRL 键时,如何在树视图中的 Qt 中实现多选?
- 使用 ctrl + C 在 python 中杀死C++进程
- C++ 上的 SendInput 不接受 Ctrl 和 Shift 帐户
- 如何在我的 Windows 应用程序中捕获按下和释放的 CTRL 键?
- while( scanf( "%d" , &n) ) { ... } 在 Linux 上按 Ctrl+D 时不退出
- 解析python文件时出现令人烦恼的Ctrl+M问题