@contextmanager<EOL>def open_file_for_write(filepath, mode=None):
stream = StringIO()<EOL>yield stream<EOL>content = stream.getvalue()<EOL>filepath = os.path.realpath(filepath)<EOL>tmpdir = tmpdir_manager.mkdtemp()<EOL>cache_filepath = os.path.join(tmpdir, os.path.basename(filepath))<EOL>debug_print("<STR_LIT>", cache_filepath, filepath)<EOL>with atomic_write(filepath, overwrite=True) as f:<EOL><INDENT>f.write(content)<EOL><DEDENT>if mode is not None:<EOL><INDENT>os.chmod(filepath, mode)<EOL><DEDENT>with open(cache_filepath, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(content)<EOL><DEDENT>file_cache[filepath] = cache_filepath<EOL>
Writes both to given filepath, and tmpdir location.

    This is to get around the problem with some NFS's where immediately reading
    a file that has just been written is problematic. Instead, any files that we
    write, we also write to /tmp, and reads of these files are redirected there.

    Args:
        filepath (str): File to write.
        mode (int): Same mode arg as you would pass to `os.chmod`.

    Yields:
        File-like object.