How to manage (pre-/post-) build settings using scripts modifying env settings?

I must state that I am relatively new to PlatformIO and an absolute beginner in Python. I can use standard settings that work for a certain platform such as Arduino Due, but I am struggling with customizing the build process.
I have gone through MaxGerhardt’s explanation for the internals of Platformio again and I have tried to be “smart”. I wanted to tell the environment to employ objcopy in order to convert a hex file form the resulting elf. I must have misunderstood something because to me it does not seem to be clear where that information had to be entered and at which time. I was under the impression that “env” seems like a giant object that contains everything there is to know about the build job, and which can be amended from any script. So I have added the the last section in my “extra_script.py” below which is referenced in platformio.ini. The question is : Why did the builder ignore that instruction? Did it come at the wrong time or from the wrong location? The main.py has a section “Allows the user to override via pre:script”. What does that mean?

The script “extra_script.py” is shown below and the relevant section is contained in the last block, after
#Make sure to obtain a hex file

from os import path
Import("env")

platform = env.PioPlatform()

env.Prepend(
    UPLOADERFLAGS=["-s", path.join(platform.get_package_dir("tool-openocd"), "scripts") or "", 
                   "-f", "interface/cmsis-dap.cfg",
                   "-c", 'set CHIPNAME at91sam3X4E', 
                   '-c', 'source [find target/at91sam3ax_4x.cfg]']
)
env.Append(
    UPLOADERFLAGS=["-c", "telnet_port disabled; program {$SOURCE} 0x80000 verify reset; shutdown"]
)
env.Replace(
    UPLOADER="openocd",
    UPLOADCMD="$UPLOADER $UPLOADERFLAGS"
)

#Make sure to obtain a hex file.
env.Append(
    ElfToHex=Builder(
        action=env.VerboseAction(" ".join([
            "$OBJCOPY",
            "-O",
            "ihex",
            "-R",
            ".eeprom",
            "$SOURCES",
            "$TARGET"
        ]), "Building $TARGET"),
        suffix=".hex"
    )
)

You are appending a Builder object named ElfToHex (which already exists in the environment in the env.BUILDERS dictionary), but this does not trigger anything. It has to be connected to a source and target file to build.

I would just recommend to use the instructions per Pre & Post Actions — PlatformIO latest documentation

Import("env")

env.AddPostAction(
    "$BUILD_DIR/${PROGNAME}.elf",
    env.VerboseAction(" ".join([
        "$OBJCOPY", "-O", "ihex", "-R", ".eeprom",
        "$BUILD_DIR/${PROGNAME}.elf", "$BUILD_DIR/${PROGNAME}.hex"
    ]), "Building $BUILD_DIR/${PROGNAME}.hex")
)

worked for me.

Thank you, I believe that I do understand. It seems that the .AddPostAction is similar to a function pointer or delegate that is added to a list for later processing. I will give it a try.