I knew already that MicroPython is cool ...
Today I learned how to redirect stdout to a bytearray in this posting:
viewtopic.php?f=2&t=5446&p=31594#p31594
I wanted to use that for *nix like command line pipe operators between more than one upysh commands.
After I learned how to use StringIO, that it is available in MicroPython and that initialization with bytearray is possible all looked good.
Then I had to learn how to prevent a function with args to run when passed as arg to another function, and learned about lambda.
I only enabled head() for pipeing, just as a proof of concept -- still unbelievable to me how easy this can be done:
Code: Select all
>>> cat("tst.txt")
first
second().
ThirD
Fourth()
>>> head(lambda: tail("tst.txt", 3), 2)
second().
ThirD
>>> head("tst.txt", 2)
first
second().
>>>
I used the DUP class from the other posting, and stuffed all else into new function openlambda:
- returns StringIO containing function output in case of lambda passed
- returns open(f) in case of filename passed
Code: Select all
$ diff upysh.py upyshlambda.py
139a140,165
>
> from io import IOBase
> from io import StringIO
>
> class DUP(IOBase):
>
> def __init__(self, s):
> self.s = s
>
> def write(self, data):
> self.s += data
> return len(data)
>
> def readinto(self, data):
> return 0
>
> def openlambda(f)
...
Code: Select all
...
> def openlambda(f):
> if type(f) == type(lambda: x):
> s = bytearray()
> prev = os.dupterm(DUP(s))
> f()
> os.dupterm(prev)
> return StringIO(s)
> else:
> return open(f)
>
141c167
< with open(f) as f:
---
> with openlambda(f) as f:
$
Originally i wanted to enable pipeing for head(), tail(), wc(), grep(), od() and perhaps cat().
Just realized that "cp(lambda: tail('tst.txt', 3), 'newfile')" would make sense as well for "tail -3 tst.txt > newfile" ...