Redirect Stderr in micropython?

712 views Asked by At

Using micro python I am trying to redirect stderr to a file however I dont have access to the run command on the board so I cannot do any shell redirect commands like >> > |. I'm curious if there is a way to do this in Micropython.

I've tried

import sys

sys.stdout = open('out.txt', 'w')
sys.stderr = sys.stdout

however

https://forum.micropython.org/viewtopic.php?t=2091 <- this discussion mentions that it is not a method supported. Im curious if y'all have any ideas. Most my googling leads itself to just python instead of micropython.

but get an error stating module has no attribute named stdout thanks

2

There are 2 answers

1
meuh On

I have not tried it, but the doc suggests you can do this if you use usys rather than sys. The open() will actually call uio.open().

1
Lixas On

This is the script that I have been using to log console output to file

import io, os

class logToFile(io.IOBase):
    def __init__(self):
        pass

    def write(self, data):
        with open("logfile.txt", mode="a") as f:
            f.write(data)
        return len(data)
# Begin loging to file
os.dupterm(logToFile())

# Stop loging to file
os.dupterm(None)