jickster wrote: ↑Thu Oct 25, 2018 3:52 pm
Then you could build your own uPy and not put them in readonly memory
Yes, but what I really want to do is using standard MicroPython and grab output sent to sys.stdout.
I just learned that this can be done!
Of course without redirecting sys.stdout, which is not possible.
The trick is to use os.dupterm() with DUP class and comment from pythoncoder:
viewtopic.php?f=2&t=3298&p=23108&hilit= ... erm#p28561
This really works, I just replaced
with
and did minor change from "help('modules')" to "help(webrepl)" (for which I had to import webrepl).
In a screen session I did:
- machine.reset()
- import dup
- print(bytes(dup.s).decode())
Here you can see the output:
Code: Select all
...
d�l��ld����l�n�����cdl�;x���#$�c;l{l{�n��D�WebREPL daemon started on ws://192.168.4.1:8266
Started webrepl in normal mode
OSError: [Errno 2] ENOENT
MicroPython v1.9.4-272-g46091b8a on 2018-07-18; ESP module with ESP8266
Type "help()" for more information.
>>> import dup
object <class 'DUP'> is of type type
__qualname__ -- DUP
readinto -- <function readinto at 0x3fff1330>
write -- <function write at 0x3fff12f0>
__module__ -- dup
__init__ -- <function __init__ at 0x3fff1300>
>>> print(bytes(dup.s).decode())
object <class 'DUP'> is of type type
__qualname__ -- DUP
readinto -- <function readinto at 0x3fff1330>
write -- <function write at 0x3fff12f0>
__module__ -- dup
__init__ -- <function __init__ at 0x3fff1300>
>>>
Summary:
Question to my original question on redirecting sys.stdout in MicroPython is "impossible.
But my real problem (capturing output sent to sys.stdout) can be solved with pagano.paganino's DUP class!
I tested this on ESP8266 as well as ESP32 MicroPython.
P.S:
For completeness:
Code: Select all
$ cat dup.py
import io
import os
import webrepl
class DUP(io.IOBase):
def __init__(self, s):
self.s = s
def write(self, data):
self.s += data
return len(data)
def readinto(self, data):
return 0
s = bytearray()
os.dupterm(DUP(s))
help(webrepl)
os.dupterm(None)
$