0

Before I start there are many other exact questions but none of the answers are adequate to my problem. The class/function log.info('foo') runs once with no problem however the second time it's called it get the error TypeError: 'str' object is not callable

I found that this question has the same problem as me, however I don't have anything called str. I have tested with with other funcions i.e war.

My code:

import praw
import sys
import traceback
from accounts import *

class logging:

    def info(self, log):
        self.info = '\033[94m'
        self.rs = '\033[0m'
        print self.info, 'INFO: ', self.rs

    def warn(self, log):
        self.warn = '\033[93m'
        self.rs = '\033[0m'
        print self.warn, 'WARNING: ', self.log, self.rs

    def critical(self, log):
        self.critical = '\033[91m'
        self.rs = '\033[0m'
        print self.critical, 'CRITICAL: ', log, self.rs

def read_accounts():
    with open('accounts.py') as f:
        for i, l in enumerate(f):
            pass

    i += 1
    accounts = {}

    while i > 0:
        ac = globals()['account_%s' %i]
        index = ac.find(':')
        uname = ac[0:index]
        password = ac[index+1:len(ac)]
        accounts[uname] = password
        i -= 1

    log.info('Usernames loaded successfully! Usernames loaded:')
    print  accounts

def main():
    log.info('Initilizing reddit accounts from file...')
    try:
        read_accounts()
    except:
        traceback.print_exc()
        log.critical('Can not read accounts! Make sure format is correct!')
        sys.exit()


if __name__ == '__main__':
    log = logging()
    main()

Also I know there is a logging module in python but I wanted to do my own thing!

Thanks in advance!

Community
  • 1
  • 1
George
  • 185
  • 1
  • 9

1 Answers1

5

The problem is that your logging class redefines all its instance methods as strings:

class logging:

    def info(self, log):
        self.info = '\033[94m'  # self.info is not a function anymore
        self.rs = '\033[0m'
        print self.info, 'INFO: ', self.rs

So the first time you call log.info, it calls the info function. The second time, it tries calling the string '\033[94m'.

Just use a different name for that instance variable in all your methods - or don't make it an instance variable at all. You're redefining it every time the method is called anyway:

class logging:

    def info(self, log):
        info_prefix = '\033[94m'  # no conflict
        self.rs = '\033[0m'
        print info_prefix, 'INFO: ', self.rs
dano
  • 91,354
  • 19
  • 222
  • 219