reload python script

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
OutoftheBOTS_
Posts: 847
Joined: Mon Nov 20, 2017 10:18 am

reload python script

Post by OutoftheBOTS_ » Thu May 05, 2022 4:34 am

I am currently using micropython running on an ESP32 for teaching high school kids robotics.

Once their robot becomes mobile we need to use webREPL to program the robot. We can upload the script with webREPL then type import script_name and it will run their script. Once the script is run then we need to do a CRTL-D in the REPL to softreset to be re run the script.

I used to have this in my boot.py to reload a script for this purpose. But for reason it now gives an error instead of reloading the script.

Code: Select all

import gc
from sys import modules
def reload(mod):
  mod_name = mod.__name__
  del sys.modules[mod_name]
  gc.collect()
  return __import__(mod_name)

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: reload python script

Post by stijn » Thu May 05, 2022 8:42 am

What error?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: reload python script

Post by pythoncoder » Thu May 05, 2022 9:28 am

There is an error in the script. It should read

Code: Select all

import gc
import sys  # Fix
def reload(mod):
  mod_name = mod.__name__
  del sys.modules[mod_name]
  gc.collect()
  return __import__(mod_name)
With the fix it works here (in main.py, which is preferred).

Code: Select all

MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information.
>>> 
>>> 
MPY: soft reboot
MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information.
>>> import arial10
>>> reload(arial10)
<module 'arial10' from 'arial10.py'>
>>> 
Peter Hinch
Index to my micropython libraries.

OutoftheBOTS_
Posts: 847
Joined: Mon Nov 20, 2017 10:18 am

Re: reload python script

Post by OutoftheBOTS_ » Thu May 05, 2022 10:40 am

Thank you. I feel a little silly not noticing that myself :(

Post Reply