Skip to content

boost::python::file_exec not fully closing file with Python 3.4.3 #52

@asies

Description

@asies

Using Python 3.4.3 and Boost 1.57.0 on 64-bit Windows 7 with Visual Studio 2013.

After boost::python::exec_file is called on a file, that file can't be modified by the program using fopen_s, I think because it is still open.

In the following example, when ModifyFile is called before executing the file, it succeeds. After the file has been executed, fopen_s returns 13 (Permission denied) and ModifyFile fails.

#include "stdafx.h"
#include "boost\python.hpp"
#include <iostream>

#define FILE_NAME         "myTest.py"

void ModifyFile( std::string newContent )
{
  FILE* myFile = nullptr;
  errno_t result = fopen_s( &myFile, FILE_NAME, "wb" );
  if ( result == 0 )
  {
    fwrite( newContent.c_str( ), sizeof( byte ), newContent.length( ), myFile );
    fclose( myFile );
    std::cout << "Success" << std::endl;
    return;
  }

  std::cout << "Failure" << std::endl;
}

int main( int argc, char** argv )
{
  Py_Initialize( );

  ModifyFile( "print(\"Hello\")" );

  boost::python::api::object mainNamespace = boost::python::import( "__main__" ).attr( "__dict__" );
  boost::python::exec_file( FILE_NAME, mainNamespace, mainNamespace );

  ModifyFile("print(\"Goodbye\")");

  Py_Finalize( );
  return 0;
}

I have tried a similar example using std::fstream to modify the file, and this doesn't seem to have the same problems.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions