PlatformIO Community

Building programmatically in another Python project?

Hope this is the correct category for my question. I’m trying to import platformio and use it in my Python project to build firmware.

I am doing something like:

from platformio.package.manager.platform import PlatformPackageManager
from platformio.platform.factory import PlatformFactory
from platformio.project.config import ProjectConfig

package_manager = PlatformPackageManager()
project_config = ProjectConfig(os.path.join("myproject", "platformio.ini")
project_config.items(env=self.env, as_dict=True)
package_manager.install(spec=platform)
platform = self.project_config.items(env="my_env", as_dict=True)["platform"]
factory = PlatformFactory.new(platform)
factory.run({"pioenv": "my_env", "project_config": "myproject"}, [], True, False, 1)

But I run into Error: BoardConfig: Board is not defined. If I run the same code in the project folder (making sure it is the current directory) it works.

I’m wondering if I am missing something or if there is a much better way of importing the project to use it as a library? I noticed PlatformFactory.run() only gives 0 or 1 for result but would be nice to capture errors as well.

Thank you for your time in advance!

I would direct questions regarding the PlatformIO core library against https://github.com/platformio/platformio-core/issues.

I came here as opening an issue there explicitly stated to:

This issue tracker is not the place for questions. If you want to ask how to do something, or to understand why something isn’t working the way you expect it to, use https://community.platformio.org

Hmmm in this case I would argue that questions regarding explicitly the PlatformIO core python code and not a “why does my PlatformIO project not build when using it normally” would be fair game. But you may be right.

@ivankravets can you have a look at why above python code that directly imports PlatformIO python libs throws that error?

1 Like

I figured this out so I thought I’d share in case a future someone encounters this.

What is happening is that at SCons build time the ProjectConfig gets initialized again and the one from PlatformFactory is ignored in https://github.com/platformio/platformio-core/blob/59e1c8872680bd2c8af01471f3351707228f2c2c/platformio/builder/tools/pioproject.py#L20-L21. This may be considered a bug…

Sorry, the lowest API for PlatformIO Core is the Command-Line interface. This is the level which we have been maintaining since 2014. We don’t recommend to use internal things from PlatformIO Core. We changed the code structure very often and it can affect you.

Do you have any issues with CLI?

Related issue

I understand. It would be cool if future development gave some thought into separating the CLI from core functionality so it could be used more as a library. For now, I’ll use as-is and make note that the classes I use may change out from under me.