我正在尝试在我的库中创建config.py,因为在每个脚本中都包含以下代码:
config = ""
try:
config = configparser.ConfigParser()
if (configFile is None) or (configFile == ""):
configReadArrayLength = len(config.read(pathABSofScript + 'config.ini'))
else:
configReadArrayLength = len(config.read(configFile))
if configReadArrayLength == 0:
print("Script could not find configuration file.")
exit(1)
except Exception as ex:
print("An exception of typ {0} occurred in config parsing function. Arguments:\n{1!r} exiting."
.format(type(ex).__name__, ex.args))
exit(1)
def get_config_value(value):
try:
return config['environment'][value]
except KeyError:
return None
except Exception as config_value_exception:
standard_logger_error(type(config_value_exception).__name__, config_value_exception.args)
我不想重复代码。因此,我遵循的步骤是:
0)结构如下:
/
scripts/
somescript.py
lib/
config.py
1)在我的somescript.py中,我输入:
sys.path.insert(0, /home/user/some/path/lib')
import config
2)config.py内容:
import configparser
config = ""
def create_config_instance(path, file_name):
try:
global config
config = configparser.ConfigParser()
configReadArrayLength = len(config.read(path + file_name))
if configReadArrayLength == 0:
raise IOError("Cannot read config file")
except Exception as ex:
raise Exception("An exception of typ {0} occurred in config parsing function. Arguments:\n{1!r} exiting.".format(type(ex).__name__, ex.args))
def get_config_value(value):
try:
global config
section = config['DEFAULT']['section_to_use']
# return config[section][value]
return "ELO"
except KeyError:
raise KeyError
except Exception as config_value_exception:
# return str(type(config_value_exception).__name__, config_value_exception.args)
raise Exception(config_value_exception)
3)somescript.py的内容
#!/usr/bin/python3.6
import unittest
import os
import sys
import platform
sys.path.insert(0, '/scripts/lib')
import logger
import config
pathABSofScript = ""
if platform.system() == "Linux":
pathABSofScript = str(os.path.realpath(__file__).rsplit('/', 1)[0]) + "/"
else:
print("Unknown linux")
exit(1)
# I'm creating instance of config.py object and passing there location of a file and file name
config_instance = config.create_config_instance(pathABSofScript, "config.ini")
# I'm trying to get value from config.ini
pathDBfile = config_instance.get_config_value("pathDBfile")
print(pathDBfile)
class TestDatabase(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
我正遇到此错误:
File "./somescript.py", line 21, in <module>
pathDBfile = config_instance.get_config_value("pathDBfile")
AttributeError: 'NoneType' object has no attribute 'get_config_value'
有人可以给我提示解决我的问题吗?