How to save information like pprint to a txt file

Asked

Viewed 301 times

0

I am creating a function to generate a log file:

def setLog(msg):
    file = open(nome_arquivo, adicionar_informacao)
    if type(msg) == str:
        msg_log = msg.encode('utf-8');
    else:
        try:
            msg_log = str(msg).encode('utf-8');
        except:
            msg_log = type(msg).__name__.encode('utf-8');
    file.write(msg_log)
    file.write("\n")
    file.close()
    echo(msg_log)

String type information is obviously saved to the file quietly, but I wanted to grab anything.

For example, I have this method:

def socketConnect(self):
        try:
            self.__ffChatSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.__ffChatSocket.connect((self.__ip, self.__port))
            self.__ffChatSocket.send(self.criarEvento("onCompleteConnection", [self.getNumeroFuturoFone()]))
            thread.start_new_thread(self.socketReceiveData, ())
        except Exception as erro:
            setLog("[ socketConnect ] erro: ")
            setLog(erro)
            self.reconectarSocket()

I send this way the error setLog(error), but I can’t catch this error, if I use the pprint I can see all the information.

I wanted something like pprint but saving in a file. txt.

1 answer

0


I figured out how to do, there is a method within the pprint itself that does this to pformat.

from pprint import pformat

saida = pformat(valor).encode('utf-8');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.