File I/O in the Python 3 C API

后端 未结 2 549
庸人自扰
庸人自扰 2021-01-02 11:25

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(ch         


        
2条回答
  •  悲哀的现实
    2021-01-02 12:01

    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();
    

提交回复
热议问题