Я пытаюсь импортировать все модули, входящие в дерево классов. Когда я импортировал их в класс, они отображаются как имеющие данные, но когда я пытаюсь получить к ним доступ из экземпляра, они отображаются пустыми.
Test_Program.py
import logging, importlib,os,sys,configparser
from Consumer_Producer import parentA
class My_Program:
def __init__(self, config_file):
try:
self.config = ci.configparser.ConfigParser()
self.config.read(config_file)
except Exception as e:
raise e
self.scan_name = "TEST_SCRIPT"
self.logger = logging.basicConfig(format='%(levelname)s - %(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S',level=logging.INFO)
self.modules_dir = None
#print(self.config.sections())
for sect in self.config.sections():
if sect == "CONFIG":
self.modules_dir = self.config.get(sect, "MODULES_DIR")
self.logger.info(self.modules_dir)
parentA.ParentA.set_config(self.config, self.scan_name)
self.logger.info(f"ParentA id at start: {id(parentA.ParentA)}")
self.parentA_init = parentA.ParentA()
self.logger.info(f"ParentA id at init: {id(self.parentA_init)}")
try:
# Import modules from each subdirectory in MODULES
for subdir in ci.os.listdir(self.modules_dir):
subdir_path = ci.os.path.join(self.modules_dir, subdir)
if ci.os.path.isdir(subdir_path):
self.import_all_modules_from_dir(subdir_path)
#print(f"ParentA id before final check: {id(parentA.ParentA)}")
self.logger.info(f"ParentA init id before final check: {id(self.parentA_init)}")
self.logger.info("Class-level registry before final check:")
self.logger.info(f"ParentA.modules_registry: {parentA.ParentA.modules_registry}")
self.logger.info("Instance-level registry before final check:")
self.logger.info(f"self.parentA_init.modules_registry: {self.parentA_init.modules_registry}")
self.logger.info("Final registry contents:")
for name, cls in self.parentA_init.modules_registry.items():
self.logger.info(f" {name}: {cls}")
except Exception as e:
self.logger.exception(e)
self.clean_shutdown()
#del self.modules_dir # NOTE: No need to keep it in memory after this
self.available_modules = self.parentA_init.get_registered_modules()
self.logger.info(self.available_modules)
self.clean_shutdown() # Just trying to get it to work up to here.
def import_all_modules_from_dir(self,directory):
"""
Imports all Python modules from the specified directory, completely skipping directories containing a given substring.
:param directory: The directory containing the modules.
"""
for filename in ci.os.listdir(directory):
path = ci.os.path.join(directory, filename)
if filename.endswith('.py') and filename != '__init__.py':
module_name = filename[:-3] # Strip .py extension
module_path = ci.os.path.dirname(path)
ci.sys.path.insert(0, module_path) # Add directory to path
self.logger.info((f"IMPORTED",ci.importlib.import_module(module_name)))
ci.sys.path.pop(0) # Remove directory from path
def clean_shutdown(self):
ci.sys.exit()
def main(self):
try:
pass
except Exception as e:
self.logger.exception(e)
if __name__ == '__main__':
test = My_Program("config.ini")
test.main()
self.logger.info("Final registry contents:")
for name, cls in self.parentA_init.modules_registry.items():
self.logger.info(f" {name}: {cls}")
Чтобы создать список доступных модулей, связанных с классами, и сохранить их, чтобы я мог взаимодействовать с ними и вызывать их по мере необходимости. Вот распечатка сообщений журнала.
Я пытаюсь импортировать все модули, входящие в дерево классов. Когда я импортировал их в класс, они отображаются как имеющие данные, но когда я пытаюсь получить к ним доступ из экземпляра, они отображаются пустыми. Test_Program.py [code]import logging, importlib,os,sys,configparser from Consumer_Producer import parentA class My_Program: def __init__(self, config_file):
#print(self.config.sections()) for sect in self.config.sections():
if sect == "CONFIG": self.modules_dir = self.config.get(sect, "MODULES_DIR") self.logger.info(self.modules_dir)
parentA.ParentA.set_config(self.config, self.scan_name) self.logger.info(f"ParentA id at start: {id(parentA.ParentA)}") self.parentA_init = parentA.ParentA() self.logger.info(f"ParentA id at init: {id(self.parentA_init)}") try: # Import modules from each subdirectory in MODULES for subdir in ci.os.listdir(self.modules_dir): subdir_path = ci.os.path.join(self.modules_dir, subdir)
if ci.os.path.isdir(subdir_path):
self.import_all_modules_from_dir(subdir_path)
#print(f"ParentA id before final check: {id(parentA.ParentA)}") self.logger.info(f"ParentA init id before final check: {id(self.parentA_init)}")
self.logger.info("Class-level registry before final check:") self.logger.info(f"ParentA.modules_registry: {parentA.ParentA.modules_registry}")
self.logger.info("Instance-level registry before final check:") self.logger.info(f"self.parentA_init.modules_registry: {self.parentA_init.modules_registry}")
self.logger.info("Final registry contents:") for name, cls in self.parentA_init.modules_registry.items(): self.logger.info(f" {name}: {cls}")
except Exception as e: self.logger.exception(e)
self.clean_shutdown()
#del self.modules_dir # NOTE: No need to keep it in memory after this
self.clean_shutdown() # Just trying to get it to work up to here.
def import_all_modules_from_dir(self,directory): """ Imports all Python modules from the specified directory, completely skipping directories containing a given substring.
:param directory: The directory containing the modules. """ for filename in ci.os.listdir(directory): path = ci.os.path.join(directory, filename)
if filename.endswith('.py') and filename != '__init__.py':
@classmethod def set_config(cls, configfile: str, scan_name=None): """ Class method to set the configuration.
:param configfile: Path to the configuration file. """ config = ci.configparser.ConfigParser() config.read(configfile) cls.config = config cls.scan_name = scan_name
@classmethod def __init__(cls): cls.logger = ci.logging.getLogger(f"TestProgram.{cls.__name__}") if not cls.config: raise ValueError("Configuration not set.")
elif not cls.logger: raise ValueError("Logger not set. ")
@classmethod def get_registered_modules(cls): """Returns the registered modules.""" return cls.modules_registry
def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) # Register the subclass ParentA.modules_registry[cls.__name__] = cls cls.logger.info(f"Registered: {cls.__name__}") # Add this line cls.logger.info(f"Current registry: {ParentA.modules_registry}") cls.logger.info(f"Registry id: {id(ParentA.modules_registry)}") [/code] Я ожидаю от этих строк: [code]self.logger.info("Final registry contents:") for name, cls in self.parentA_init.modules_registry.items(): self.logger.info(f" {name}: {cls}") [/code] Чтобы создать список доступных модулей, связанных с классами, и сохранить их, чтобы я мог взаимодействовать с ними и вызывать их по мере необходимости. Вот распечатка сообщений журнала. [code]2024-11-10 18:13:56,390 - Test_Program - INFO - [TARGET 1] DEFAULT: 2024-11-10 18:13:56,390 - Test_Program - INFO - [TARGET 1] TARGETS: 2024-11-10 18:13:56,390 - Test_Program - INFO - [TARGET 1] CONFIG: 2024-11-10 18:13:56,390 - Test_Program - INFO - /Consumer_Producer 2024-11-10 18:13:56,391 - Test_Program - INFO - ParentA id at start: 40933232 2024-11-10 18:13:56,391 - Test_Program - INFO - ParentA id at init: 139938483760976 2024-11-10 18:13:57,885 - Test_Program.ParentA.MirageA - INFO - Registered: MirageA 2024-11-10 18:13:57,885 - Test_Program.ParentA.MirageA - INFO - Current registry: {'MirageA': } 2024-11-10 18:13:57,885 - Test_Program.ParentA.MirageA - INFO - Registry id: 139938483833152 2024-11-10 18:13:57,885 - Test_Program.ParentA.MirageA.Child3 - INFO - Registered: child3 2024-11-10 18:13:57,885 - Test_Program.ParentA.MirageA.Child3 - INFO - Current registry: {'MirageA': , 'child3': } 2024-11-10 18:13:57,885 - Test_Program.ParentA.MirageA.Child3 - INFO - Registry id: 139938483833152 2024-11-10 18:13:57,885 - Test_Program - INFO - ('IMPORTED', ) 2024-11-10 18:13:57,891 - Test_Program.ParentA.MirageA.Child1 - INFO - Registered: child1 2024-11-10 18:13:57,891 - Test_Program.ParentA.MirageA.Child1 - INFO - Current registry: {'MirageA': , 'child3': , 'child1': } 2024-11-10 18:13:57,891 - Test_Program.ParentA.MirageA.Child1 - INFO - Registry id: 139938483833152 2024-11-10 18:13:57,891 - Test_Program - INFO - ('IMPORTED', ) 2024-11-10 18:13:57,892 - Test_Program.ParentA.MirageA.Child2 - INFO - Registered: child2 2024-11-10 18:13:57,893 - Test_Program.ParentA.MirageA.Child2 - INFO - Current registry: {'MirageA': , 'child3': , 'child1': , 'child2': } 2024-11-10 18:13:57,893 - Test_Program.ParentA.MirageA.Child2 - INFO - Registry id: 139938483833152 2024-11-10 18:13:57,893 - Test_Program - INFO - ('IMPORTED', ) 2024-11-10 18:13:57,895 - Test_Program - INFO - ('IMPORTED', ) 2024-11-10 18:13:57,895 - Test_Program - INFO - ParentA init id before final check: 139938483760976 2024-11-10 18:13:57,895 - Test_Program - INFO - Class-level registry before final check: 2024-11-10 18:13:57,895 - Test_Program - INFO - ParentA.modules_registry: {} 2024-11-10 18:13:57,895 - Test_Program - INFO - Instance-level registry before final check: 2024-11-10 18:13:57,895 - Test_Program - INFO - self.parentA_init.modules_registry: {} 2024-11-10 18:13:57,895 - Test_Program - INFO - Final registry contents: 2024-11-10 18:13:57,895 - Test_Program - INFO - {} [/code] Так почему же окончательное содержимое реестра экземпляра моего класса пустое, хотя в самом классе оно отображается как полное?
Это в основном суммирует мой вопрос.
Я новичок, поэтому извините, если я чего-то не понимаю.
p.s. если бы кто-нибудь мог объяснить мне exec() в этом примере (вместо импорта), это было...
У меня есть общий вопрос при работе над более крупными проектами с использованием кода Visual Studio, где я хочу избежать написания одного и того же импорта и определения констант в каждом файле Python. Допустим, у меня есть следующая структура...
У меня есть общий вопрос при работе над более крупными проектами с использованием кода Visual Studio, где я хочу избежать написания одного и того же импорта и определения констант в каждом файле Python. Допустим, у меня есть следующая структура...
У меня есть общий вопрос при работе над более крупными проектами с использованием кода Visual Studio, где я хочу избежать написания одного и того же импорта и определения констант в каждом файле Python. Допустим, у меня есть следующая структура...
У меня есть общий вопрос при работе над более крупными проектами с использованием кода Visual Studio, где я хочу избежать написания одного и того же импорта и определения констант в каждом файле Python. Допустим, у меня есть следующая структура...