← index #3509Issue #2322
Duplicate · high · value 2.807
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: can't import frozen modules from a script that was executed from a file

closedby dpgeorgeopened 2016-08-15updated 2021-12-17
bugport-unix

The unix port can import frozen modules (str and mpy) from the REPL but it can't import them when executing a file (eg from ./micropython test.py). This is because when a file is executed from the command line the first entry in sys.path (which is originally the empty string '') is replaced by the base path of the executing file. This is the correct (CPython) behaviour.

But it means that frozen modules can no longer be found in the path -- they require the empty string in the path in order for them to be found in the import search (note that bare-metal ports always have '' in the path so they are ok).

Some ways to fix:

  1. Add a hack to the import machinery to always search frozen modules.
  2. Add a special directory to sys.path (eg :frozen:/) and prefix all the filenames in the list of frozen files with this special directory. The benefit of this is that it would allow the user to control the order of search when looking for frozen modules.

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