Builder GET monitor_port value from INI

any easy solution to get monitor_port value from platformio.ini file?

If the value is explicitly set in the platformio.ini one can do

print("Monitor port is %s " % env.GetProjectOption("monitor_port"))

Of that option is not set it will be empty.

If the monitor port is is identical to the upload port one can do

from import AutodetectUploadPort
print("Port is %s " % env.subst("$UPLOAD_PORT"))

Otherwise one would have to do the same logic that the pio device monitor command does to figure out the monitor port

Here’s a minimal way with the original pio monitor logic


from platformio.commands.device import helpers as device_helpers
from platformio import exception, fs, util

platform = env.PioPlatform()
project_options = device_helpers.get_project_options(env["PIOENV"])
kwargs = {}
monitor_port = ""
if "monitor_port" in project_options: 
    # use predefined value 
    monitor_port = project_options["monitor_port"]
else: # search
    ports = util.get_serial_ports(filter_hwid=True)
    if len(ports) == 1:
        kwargs["port"] = ports[0]["port"]
        monitor_port = kwargs["port"]
    elif "platform" in project_options and "board" in project_options:
        board_hwids = device_helpers.get_board_hwids(
        for item in ports:
            for hwid in board_hwids:
                hwid_str = ("%s:%s" % (hwid[0], hwid[1])).replace("0x", "")
                if hwid_str in item["hwid"]:
                    kwargs["port"] = item["port"]
            if kwargs["port"]:
        # contains "port" entry
        monitor_port = kwargs["port"]

print("Final monitor port: %s" % monitor_port)

if I use that as extra script while having no monitor_port option set, I get the automatic upload port, and if I have monitor_port set, it gives me that. Works in both cases.

Thanks Max !!!

env.GetProjectOption(“monitor_port”) work fine

But if it’s not set it in the platformio.ini it won’t work :confused:

no problems :slight_smile:

I need this to reset Pico to boot-uf2 if is used USB stdio ( without button and cable )

@maxgerhardt, I wonder about this part in your example

monitor_port = project_options[“monitor_port”]

In the general case, the value of ‘monitor_port’ is defined as a regex (glob), not as a port name, right? Will that code work correctly for example if monitor_port = COM[234]?

If it’s indeed a glob expression, how would you go for determining the port under Windows?

(Found this thread due to a problem I just encountered with the U2F loader which uses the port to force the Pico into BOOT mode, no intention to nit pick old posts ;-))

Yes, in case of a GLOB expresionn, additional logic is missing, see

Thanks @maxgerhardt. This is exactly what I was looking for.