← index #3509Issue #6419
Duplicate · high · value 1.170
QUERY · ISSUE

Mpy modules cannot be imported (sys.path missing '') when running file outside of cwd

openby ryannathansopened 2017-12-21updated 2021-12-17
py-core

Found on unix port - protostuffer is a single .py file in the modules folder, built in at compile time

./micropython
MicroPython v1.9.3-7-g46e9ef6-dirty on 2017-12-21; linux version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import protostuffer
>>>
./micropython ../../tests/protostuffer-tests/header.py
Traceback (most recent call last):
  File "../../tests/protostuffer-tests/header.py", line 1, in <module>
ImportError: no module named 'protostuffer'

To fix

./micropython -i ../../tests/protostuffer-tests/header.py
Traceback (most recent call last):
  File "../../tests/protostuffer-tests/header.py", line 1, in <module>
ImportError: no module named 'protostuffer'
MicroPython v1.9.3-7-g46e9ef6-dirty on 2017-12-21; linux version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import protostuffer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: no module named 'protostuffer'
>>> import sys
>>> sys.path.append('')
>>> import protostuffer
>>>
CANDIDATE · ISSUE

unix: sys.path affects loading of frozen modules

closedby jimmoopened 2020-09-08updated 2021-12-17

Example:

  1. Add a frozen module to unix/windows port.
  2. At the repl:
import mymodule # works
  1. create demo.py containing
import mymodule

Run

$ ./micropython ~/mpy/demo.py
Traceback (most recent call last):
  File "/home/jimmo/mpy/demo.py", line 5, in <module>
ImportError: no module named 'mymodule'

The underlying issue here is that the unix port, when running normally has sys.path=["", "~/.micropython/lib:/usr/lib/micropython"], and when running with a path to /path/to/demo.py has sys.path=["/path/to", "~/.micropython/lib:/usr/lib/micropython"]

When import mymodule is executed, it's trying to load mp_frozen_stat("/path/to/mymodule"), but the frozen module is just named "mymodule".

I'm not sure if the fix here is to improve the frozen module matching (i.e. assume that all frozen modules are in all sys.paths), or to always have "" as the final entry in sys.path? Or something else? Need to consider how thiss interact with the behavior where filesystem modules override frozen modules of the same name.

This came from the forum: https://forum.micropython.org/viewtopic.php?f=12&t=8995&p=50840#p50840

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied