How to use Python argparse in extra_scripts

Hello
I have some extra_scripts run in pre: mode doing some project specific tasks. Now I want to add ability to run it outside of build process, to test results. When I have added argument to script (using argparse) to have some “dry run” option - whole build process fails:

Processing lang_pl (platform: espressif8266@4.2.1; framework: arduino; board: nodemcuv2)
------------------------------------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
usage: scons.py [-h] [-d]
scons.py: error: unrecognized arguments: -Q --warn=no-no-parallel-support --jobs 8 --sconstruct /home/viciu/.platformio/penv/lib/python3.10/site-packages/platformio/builder/main.py PIOVERBOSE=0 ISATTY=1 PIOENV=bGFuZ19wbA== PROJECT_CONFIG=L2hvbWUvdmljaXUvRG9jdW1lbnRzL2Rldi9uYW1mL3BsYXRmb3JtaW8uaW5p PROGRAM_ARGS=W10= BUILD_SCRIPT=L2hvbWUvdmljaXUvLnBsYXRmb3JtaW8vcGxhdGZvcm1zL2VzcHJlc3NpZjgyNjZAc3JjLWViNzQ5NWY4OGViMGFmYTE4ZmVkZmY5OGJmYjVlNDBmL2J1aWxkZXIvbWFpbi5weQ==

Offending code is:

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dry", help="Test run - display missing keys, not write any files", action="store_true")
args = parser.parse_args()

Just last line is causing problems (without parsing args project is being built).

Is there a solution allowing to scripts being used in extra_scripts to accept options? I don’t want to add option to call from platformio.ini I just need a way to let script run outside of build process, in dry-run mode.

Or only solution is to extract common code to some library and have two scripts, one used in build process and second one to do test runs?

1 Like
try:
   Import("env")
   IS_SCONS_BUILD = True
except:
   IS_SCONS_BUILD = False

if IS_SCONS_BUILD:
  # only do PlatformIO specific stuff
else:
  # only do general script stuff (argparse, etc)