0

I am trying to read some values from a config file in python inside a class and then i am trying to access these variables inside one more function inside the same class. I have tried the below code but there seems to be something wrong in my code. Here is what i tried:

class CLEAN():
    def __init__(self):
        parser = argparse.ArgumentParser(description='Remove inactive users from artifactory')
        parser.add_argument('-f', '--config_file', dest='config_file', default="", required=True, action="store", help='the config file with creds')
        parser.add_argument('-d', '--log_dir', dest='log_dir', default="", required=True, action="store", help='the logs dir')
        parsers = parser.parse_args()

        self.config_file = parsers.config_file.strip()
        self.log_dir = parsers.log_dir.strip()

        if not os.path.exists(self.log_dir):
            os.mkdir(self.log_dir)

        with open('config.ini', 'r') as myfile:
            for line in myfile:
                if 'instance' in line:
                     instance = line.split('=')[1]
                if 'user' in line:
                    user = line.split('=')[1]
                if 'user_api' in line:
                     user_api = line.split('=')[1]

    def print_values(self):
        logger.info(self.instance)
        logger.info(self.user)
        logger.info(self.user_api)`

This part of the code is followed by main() The error that i am getting is

Traceback (most recent call last):
 File "clean.py", line 48, in <module>
    c.main()
  File "clean.py", line 44, in main
    self.print_values()
  File "clean.py", line 39, in print_values
   logger.info(self.instance)
AttributeError: CLEAN instance has no attribute 
'instance'


cat config.ini
instance=xxxxx
user=abc
user_api=xxxx
2
  • You have not initialized instance properly, use: self.instance = line.split('=')[1] Commented Jan 24, 2019 at 8:59
  • 1
    Your code creates local (function) variables, not object attributes. Commented Jan 24, 2019 at 8:59

2 Answers 2

2

You need to add self.:

self.instance = line.split('=')[1]

Same for user and user_api.

On the flip side, you don't need self for config_file or log_dir if you're not going to use those variables outside of that method.

As bruno says, using ConfigParser:

from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')
print(config['section']['instance'])  # xxxxx

This requires adding a line [section] to the top of the config file. Any title will do, but a section header is required.

Then you can you self.config = config['section'] and access the values as self.config['instance'].

Sign up to request clarification or add additional context in comments.

3 Comments

Haha thanks @brunodesthuilliers, that was pretty critical.
ohh, this works perfectly, bdw both user and user_api display the same value. My guess is because both have the term user in it, the values overlap..how can i correct this in my code
@panda cf my answer - use the stlib's ConfigParser instead.
0

Here:

     with open('config.ini', 'r') as myfile:
        for line in myfile:
            if 'instance' in line:
                 instance = line.split('=')[1]
            if 'user' in line:
                user = line.split('=')[1]
            if 'user_api' in line:
                 user_api = line.split('=')[1]

You are creating local variables, not instance attributes. You have to assign to self.instance, self.userandself.user_api` instead.

Also, with your current code, there's no garantee that those attributes will be set (if the "user", "user_api" or "instance" words are not found in the file), so you want to first set those attributes to default values, ie:

     # which default value makes sense is up to you
     self.instance = None
     self.user = None
     self.user_api = None

     with open('config.ini', 'r') as myfile:
        for line in myfile:
            if 'instance' in line:
                 self.instance = line.split('=')[1]
            if 'user' in line:
                self.user = line.split('=')[1]
            if 'user_api' in line:
                 self.user_api = line.split('=')[1]

Also, python has a ConfigParser class that knows how to deal with ini files, so you'd probably be better using this instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.