How to save information equal to pprint in a txt file

0

I'm 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 in the file quietly, but I wanted to catch 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 the error setLog (error), but I can not get this error, if I use pprint I can see all the information.

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

    
asked by anonymous 22.09.2017 / 16:22

1 answer

0

I discovered how to do it, there is a method inside the pprint itself that does this pformat.

from pprint import pformat

saida = pformat(valor).encode('utf-8');
    
22.09.2017 / 18:28