0

I would like to redirect stdout and stderr to socket.send as an encoded string.

I'm working on Windows 10. I have seen solutions online such as Python. Redirect stdout to a socket and How to constantly send STDOUT to my python TCP server?.

These solutions are not redirecting stderr and I get the exception below.

The farthest I got is this:

import socket, sys, argparse

class stdout_():

    def __init__(self, sock_resp):
        self.sock_resp = sock_resp

    def write(self, mes):
        self.sock_resp.send(mes.encode())


SERVER = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (SERVER, PORT)

srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Start server")
old_out = sys.stdout

srv.bind(ADDR)
srv.listen()
sock_resp, addr_resp = srv.accept()
new_out = stdout_(sock_resp)
sys.stdout = new_out
# sys.stdout = sock_resp ### sock_object has no attribute 'write'
while 1:
    try:
        a = sock_resp.recv(1024).decode()
        parser = argparse.ArgumentParser()
        parser.parse_args(a.split())
        
    except socket.timeout:
        #print('server timeout!!' + '\n')
        continue

But this doesn't redirect stderr, and whenever the argparse print is getting to the client's console I get this exception on the server's console:

AttributeError: 'stdout_' object has no attribute 'flush'

0 Answers0