File I/O in the Python 3 C API

随声附和 提交于 2019-11-29 18:59:18

问题


The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects.

Before, in 2.X, you could use

PyObject* PyFile_FromString(char *filename, char *mode)

to create a Python file object, e.g:

PyObject *myFile = PyFile_FromString("test.txt", "r");

...but such function no longer exists in Python 3.0. What would be the Python 3.0 equivalent to such call?


回答1:


You can do it the old(new?)-fashioned way, by just calling the io module.

This code works, but it does no error checking. See the docs for explanation.

PyObject *ioMod, *openedFile;

PyGILState_STATE gilState = PyGILState_Ensure();

ioMod = PyImport_ImportModule("io");

openedFile = PyObject_CallMethod(ioMod, "open", "ss", "foo.txt", "wb");
Py_DECREF(ioMod);

PyObject_CallMethod(openedFile, "write", "y", "Written from Python C API!\n");
PyObject_CallMethod(openedFile, "flush", NULL);
PyObject_CallMethod(openedFile, "close", NULL);
Py_DECREF(openedFile);

PyGILState_Release(gilState);
Py_Finalize();



回答2:


This page claims the API is:

PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd);

Not sure if that means it's not possible to have Python open the file from the filename, but that should be trivial to do yourself, in C.



来源:https://stackoverflow.com/questions/898136/file-i-o-in-the-python-3-c-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!