I can’t interact with micropython by Popen

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
User avatar
aivarannamaa
Posts: 36
Joined: Fri Sep 22, 2017 3:19 pm
Location: Estonia
Contact:

Re: I can’t interact with micropython by Popen

Post by aivarannamaa » Sat May 16, 2020 1:17 pm

@rockindy, if you are on Unix, then you can make it work via pty. Here is my own experiment of reading python commands from sys.stdin and forwarding them to micropython in a subprocess:

Code: Select all


import subprocess
import os
import pty

master, slave = pty.openpty()

proc = subprocess.Popen(["micropython"],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        stdin=slave,
                        universal_newlines=True)

stdin = os.fdopen(master, 'w')


def keep_reading(stream):
    while True:
        data = stream.read(1)
        if data:
            print(data, end="")
        else:
            print("done")
            break

import threading
threading.Thread(target=keep_reading, args=[proc.stdout]).start()

from time import sleep
while True:
    # allow stdout reader to complete
    # TODO: should be dome properly with select.select
    sleep(0.1)
    
    cmd = input()
    if not cmd:
        break
    
    stdin.write(cmd + "\n")
    stdin.flush()

I don't know how to get rid of stdin echoed in stdout, though. Tried this but without success.

Post Reply