Page 1 of 1

Frozen bytecode main.py

Posted: Wed Aug 15, 2018 6:47 am
by ajie_dirgantara
I am on production phase and would like to froze main.py and other modules into the micropython binary file, so after it burned into flash it will run directly. is this possible?

Re: Frozen bytecode main.py

Posted: Wed Aug 15, 2018 7:15 am
by Roberthh
The resepctive code is around https://github.com/micropython/micropyt ... main.c#L68
There you see, that a file called _boot.py is run from flash, and that boot.py and main.py are run form the file system. You can either change the call for boot.py and main.py into pyexec_frozen_module(), or put the start of your modules into _boot.py.

Re: Frozen bytecode main.py

Posted: Thu Aug 16, 2018 8:00 am
by ajie_dirgantara
Roberthh wrote:
Wed Aug 15, 2018 7:15 am
The resepctive code is around https://github.com/micropython/micropyt ... main.c#L68
There you see, that a file called _boot.py is run from flash, and that boot.py and main.py are run form the file system. You can either change the call for boot.py and main.py into pyexec_frozen_module(), or put the start of your modules into _boot.py.
Ok, so in short, after adding my main.py in "modules" directory, and then by modify the _boot.py by add "import main.py" line at below is enough?

Code: Select all

import gc
gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
import uos
from flashbdev import bdev

try:
    if bdev:
        uos.mount(bdev, '/')
except OSError:
    import inisetup
    inisetup.setup()

gc.collect()

import main.py

Re: Frozen bytecode main.py

Posted: Thu Aug 16, 2018 8:15 am
by Roberthh
That should work. I only would not call that file main.py, to avoid conflicts. You can give is any other name. In addition you can have a main.py in your file system, which then might be empty. abd obviously, if your file is called "myfile.py", the statement should read:
import myfile

Re: Frozen bytecode main.py

Posted: Thu Aug 16, 2018 8:34 am
by ajie_dirgantara
ok, this is a bit out of topic, but can we also froze "webrepl_cfg.py", so it doesn't need to be configured one by one?

Re: Frozen bytecode main.py

Posted: Thu Aug 16, 2018 8:59 am
by Roberthh
you can freeze any python script, which is about to be imported. And you can simply try it.

Re: Frozen bytecode main.py

Posted: Sat Aug 18, 2018 8:22 am
by pythoncoder
The approach I have used is to have _boot.py create main.py if it doesn't exist. The new main.py imports my module (mqtt).

_boot.py:

Code: Select all

import gc
gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
import uos
from flashbdev import bdev

try:
    if bdev:
        uos.mount(bdev, '/')
except OSError:
    import inisetup
    inisetup.setup()

try:
    uos.stat('/main.py')
except OSError:
    with open("/main.py", "w") as f:
        f.write("""\
import mqtt
""")

gc.collect()