我有一些严重的麻烦越来越蟒蛇2的基础C++发动机的工作Python3.我知道整个IO堆已经改变,但是我的一切似乎只是尝试最终失败。下面是预代码(Python2)和后代码(Python3).我希望有人可以帮我弄清楚我在做什么错误的。我也使用 boost::python 来控制所引用。

该程序应该载蟒蛇的对象进入存储器通过地图,然后使用的运行的功能,然后,它认为该文件加载存储和运行。我根据我的代码一个例从delta3d python经理,他们负载一个文件,而运行。我还没有看到任何东西相当于在Python3.


Python2码从这里开始:

    // what this does is first calls the Python C-API to load the file, then pass the returned
    // PyObject* into handle, which takes reference and sets it as a boost::python::object.
    // this takes care of all future referencing and dereferencing.
    try{
        bp::object file_object(bp::handle<>(PyFile_FromString(fullPath(filename), "r" )));
        loaded_files_.insert(std::make_pair(std::string(fullPath(filename)), file_object));
    }
    catch(...)
    {
        getExceptionFromPy();
    }

接下来我加载的文件自std::地图和试图执行它:

    bp::object loaded_file = getLoadedFile(filename);
    try
    {
        PyRun_SimpleFile( PyFile_AsFile( loaded_file.ptr()), fullPath(filename) );
    }
    catch(...)
    {
        getExceptionFromPy();
    }

Python3码从这里开始:这是我迄今为止基于关闭一些建议,这里... 所以问题 载荷:

        PyObject *ioMod, *opened_file, *fd_obj;

        ioMod = PyImport_ImportModule("io");
        opened_file = PyObject_CallMethod(ioMod, "open", "ss", fullPath(filename), "r");

        bp::handle<> h_open(opened_file);
        bp::object file_obj(h_open);
        loaded_files_.insert(std::make_pair(std::string(fullPath(filename)), file_obj));

运行:

    bp::object loaded_file = getLoadedFile(filename);
    int fd = PyObject_AsFileDescriptor(loaded_file.ptr());
    PyObject* fileObj = PyFile_FromFd(fd,fullPath(filename),"r",-1,"", "\n","", 0);

    FILE* f_open = _fdopen(fd,"r");

    PyRun_SimpleFile( f_open, fullPath(filename) );

最后,一般的状态的程序在这一点是该文件被装载在如 TextIOWrapper 而在运行:部分fd返回总是3和由于某种原因 _fdopen 永远不能打开 FILE 这意味着我不能做这样的事情 PyRun_SimpleFile.错误本身是一个调试 ASSERTION_fdopen.是否有一个更好的方式来做到这一切,我真的很感谢任何的帮助。

如果你想看到完整的程序的Python2版本,它是在

有帮助吗?

解决方案

因此,这个问题是相当难以理解,我很抱歉,但是我发现我的老的代码不是相当的工作作为我的预期。这里就是我想代码做到的。负载的蟒蛇的文件存入内存,存放它进入地图,然后在稍后的日期执行这些代码存储器中。我完成了这一点不同于我期望,但它很有意义。

  1. 打开文件使用ifstream,参见下面的代码
  2. 转换char入一个增强::python::str
  3. 执行加强::python::str有提升::python::exec
  4. 利???

步骤1)

vector<char> input;
ifstream file(fullPath(filename), ios::in);
if (!file.is_open())
{
    // set our error message here
    setCantFindFileError();
    input.push_back('\0');
    return input;
}

file >> std::noskipws;
copy(istream_iterator<char>(file), istream_iterator<char>(), back_inserter(input));
input.push_back('\n');
input.push_back('\0');

步骤2) bp::str file_str(string(和输入[0]));loaded_files_.插入(std::make_pair(std::string(完整路径(filename)),file_str));步骤3)

bp::str loaded_file = getLoadedFile(filename);
// Retrieve the main module
bp::object main = bp::import("__main__");
// Retrieve the main module's namespace
bp::object global(main.attr("__dict__"));
bp::exec(loaded_file, global, global);

完整的代码是位于 :

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top