-
Notifications
You must be signed in to change notification settings - Fork 0
The IO (Input/Output) module in aplustools
serves as a robust utility for managing various input and output operations within your application. It combines the functionalities of both the environment
and loggers
modules, offering a comprehensive toolkit for file system management and advanced logging. This module simplifies tasks such as directory navigation, file manipulation, and setting working directories, while also providing sophisticated logging mechanisms for capturing and categorizing application logs. Whether you need to handle file operations or maintain detailed logs of your application's runtime behavior, the IO module is equipped to facilitate these processes efficiently, enhancing both the development experience and the functionality of your applications.
This module provides a set of tools for interacting with the file system, managing paths, and retrieving system information. It includes utilities for working directory management, path manipulation, file operations, and system info retrieval.
- set_working_dir_to_main_script_location(): Sets the working directory to the main script's location, considering both normal and frozen (PyInstaller) scenarios.
- change_working_dir_to_script_location(): Changes the working directory to the calling script's directory.
- change_working_dir_to_temp_folder(): Sets the working directory to the system's temporary folder.
- change_working_dir_to_userprofile_folder(folder: str): Changes the working directory to a specified folder within the user's profile directory.
- absolute_path(relative_path: str, file_path: str) -> str: Resolves an absolute path from a given relative path and a file path.
- remv(paths: Union[str, list]): Removes files or directories.
- contains_only_directories(path: str) -> bool: Checks if a directory contains only directories.
- is_accessible(path: str): Verifies if a path is accessible.
- is_empty_directory(path: str) -> bool: Determines if a directory is empty.
A tool for converting class instances into dictionaries combining their public methods and attributes. The decorator transforms a class so that when instantiated, it returns a dictionary where public attributes are accessible as key-value pairs and methods can be invoked directly.
- cls (class): The class to be transformed.
This decorator is experimental. It's currently in development and might not work as expected in all scenarios.
@functionize
class MyClass:
def __init__(self, value):
self.value = value
def greet(self):
return f"Hello, value is {self.value}"
instance_dict = MyClass(42)
print(instance_dict['value']) # Access attribute
print(instance_dict['greet']()) # Call method
A tool designed to enforce encapsulation in Python classes. It wraps a class in a cover class, which exposes only the public attributes and methods of the original class, disallowing direct access to its private members.
- cls (class): The class to be transformed.
This decorator doesn't work with subclasses. Only the BaseClass will be strict so the subclasses won't be able to access any private attributes from it. Also, if ever needed you can "easily" circumvent the cover class like this:
cover_instance = Instance()
bound_method = cover_instance.public_method
original_object = bound_method.__self__ # This approach is only applicable to instance methods, which are neither static nor class methods.
private_member = original_object._private # Static methods do not have a reference to an instance of the class (the 'self' object), as they belong to the class itself.
# Class methods have a reference to the class ('cls'), not to any particular instance, so they cannot access instance-specific attributes.
print(private_member) # This means that for static and class methods, accessing instance-specific data like '__self__' or instance-private members is not possible.
@strict
class MyClass:
def __init__(self):
self.public_attr = "Public"
self._private_attr = "Private"
def public_method(self):
return "This is public"
instance = MyClass()
print(instance.public_attr) # Accessible
print(instance.public_method()) # Accessible
# instance._private_attr # Would raise AttributeError
Represents a file system path and provides methods to interact with it.
- exists() -> bool: Checks if the path exists.
- is_file() -> bool: Determines if the path is a file.
- is_directory() -> bool: Determines if the path is a directory.
- create_directory(): Creates a directory at the path.
- list_files() -> list: Lists files in the directory.
- list_subdirectories() -> list: Lists subdirectories in the directory.
- get_size() -> Optional[int]: Gets the file size in bytes.
- rename(new_path: str): Renames the path.
Provides information about the system.
- get_os(): Retrieves the operating system name.
- get_os_version(): Gets the version of the operating system.
- get_cpu_arch(): Returns the CPU architecture.
- get_cpu_brand(): Obtains the CPU brand and model.
- get_system_theme(): Determines the system's theme (Light/Dark).
from aplustools.io.environment import set_working_dir_to_main_script_location, change_working_dir_to_script_location, Path, copy, move
# Setting working directory
set_working_dir_to_main_script_location()
change_working_dir_to_script_location()
# Path operations
path = Path("./some_folder")
if not path.exists():
path.create_directory()
copy("./file1.txt", "./some_folder")
move("./some_folder/file1.txt", "./file1_moved.txt")
from aplustools.io.environment import print_system_info
# Print system information
print_system_info()
In this usage example, various functionalities of the module are demonstrated, including working directory manipulation, file and directory operations with the Path
class, and retrieving system information.
The loggers
module offers flexible logging capabilities, capturing and classifying log messages from your application. It supports different log levels, file logging, and capturing standard output. The module is designed to be versatile, supporting various logging strategies.
An Enum representing different types of log messages.
-
NONE
: No specific type. -
INFO
: Informational messages. -
DEBUG
: Debug messages. -
WARN
: Warning messages. -
ERR
: Error messages. -
ANY
: Any type of message.
Basic logger class for writing log messages to a file.
- log(message: str): Logs a message to the file.
- close(): Closes the log file.
Extended logger class capturing and logging standard output.
- write(message: str): Writes and logs messages captured from stdout.
- flush(): Ensures that the buffer is flushed.
Advanced logger with message type classification and different logging behaviors based on message types.
- log(message: str, type: LogType): Logs a message with an optional type.
- _add_type(message: str, log_type: Optional[LogType]): Adds type information to a message based on the log type.
A comprehensive logger providing a full type system on top of the print system. (Not yet implemented)
A function to redirect and monitor stdout to a logger.
- monitor_stdout(log_file: Optional[str], logger: Optional[Type[Logger]]) -> Union[TextIO, Type[Logger]]: Monitors and logs stdout messages.
A utility function to classify the type of a message based on its content.
-
classify_type_stan(message: str) -> Tuple[LogType, str]: Classifies a message into a
LogType
.
from aplustools.io.loggers import Logger, PrintLogger, TypeLogger, LogType
# Basic file logging
logger = Logger("app.log")
logger.log("Starting application")
logger.log("An error occurred", LogType.ERR)
logger.close()
# Capturing and logging stdout
print_logger = PrintLogger("output.log", capture_stdout=True)
sys.stdout = print_logger
print("This message is logged")
# Advanced logging with message type classification
type_logger = TypeLogger("typed.log")
type_logger.log("Debugging info", LogType.DEBUG)
type_logger.log("Warning: Potential issue", LogType.WARN)
In these examples, various logging strategies are demonstrated, from simple file logging to advanced type-based logging. The module is designed to be easily integrated into applications for robust logging capabilities.