pfalcon / utemplate

Micro template engine in Python with low memory usage, designed for Pycopy, a minimalist Python dialect, but also compatible with other Pythons.
https://github.com/pfalcon/pycopy
76 stars 8 forks source link

compile() failure when run via mpremote mount on Pico #19

Open jfbauer432 opened 1 year ago

jfbauer432 commented 1 year ago

I ran into am issue when using utemplate on a Raspberry Pi Pico. I was using the mpremote command with the mount option. Something like

mpremote mount . run main.py

If you are nor familiar with that, it has the Pico mount a directory ('.' in this case) on the host and then run code from there. Using this you can run your code without having to upload to the Pico first.

It fails in source.py at the

for l in self.file_in:

line with an

TypeError: 'RemoteFile' object isn't iterable.

I presume that files opened on the host are of type RemoteFile and that you can't just iterate over each line like it was a local file. I quick fix is to make the following change

     def compile(self):
         self.header()
-        for l in self.file_in:
-            self.parse_line(l)
+        try:
+            for l in self.file_in:
+                self.parse_line(l)
+        except TypeError:
+            lines = self.file_in.readlines()
+            for l in lines:
+                self.parse_line(l)
         self.close_literal()
         return self.seq

It is a bit slow but it works -- maybe I should just always upload to the Pico :-)

Due to the above error, it created but did not finish writing the .py version of the template file (it only had the initial comment line). So later runs try to import it and they fail in compiled.py when trying to access the .render attribute AttributeError: 'module' object has no attribute 'render'. It might be helpful to others in the future, it that could be caught and a better error presented.