LifeAdventurer / Moonafly

Moonafly is not just a discord bot.

Home Page:https://moonafly.github.io/docs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feat: add color to stderr output to the terminal

LifeAdventurer opened this issue · comments

commented

After my research, using pty in Linux can print the original color correctly.
The following is simple implemented code.

import os
import pty
import sys
import select
import subprocess

EXEC_PATH = ["python", "bot.py"]


master, slave = pty.openpty()
subprocess_args = {
    # "stderr": subprocess.PIPE,
    "stderr": slave,
    "encoding": "utf-8",
    "bufsize": 0,
}

pipe = subprocess.Popen(EXEC_PATH, **subprocess_args)

while True:
    reads, _, _ = select.select([master], [], [])
    for fd in reads:
        out = os.read(fd, 1024).decode('utf-8').strip()
        print(out)
        
        if "Restarting Moonafly..." in out:
            pipe.kill()
            pipe = subprocess.Popen(EXEC_PATH, **subprocess_args)
            continue
        elif "Moonafly stopped by command" in out:
            print("Moonafly stopped by command")
            os._exit(0)

Unfortunately, pty didn't support Windows.
I find pywinpty implemented pty on Windows.
But I didn't test on windows.

I think it have another way like using hacking trick to force discord.py print ANSI color in pipe.
This way should work both on Windows and Linux.

commented

you can open an issue and handle it

commented

I tried pywinpy and it didn't work. I'm not sure if it was my problem.