Skip to content

Commit 6d8e49e

Browse files
authored
Update main.py
1 parent 176ed52 commit 6d8e49e

File tree

1 file changed

+32
-23
lines changed

1 file changed

+32
-23
lines changed

main.py

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
"""Script runner that executes multiple Python scripts in sequence.
2-
1+
#!/usr/bin/env python3
2+
"""
3+
Script runner that executes multiple Python scripts in sequence.
34
This module provides functionality to run multiple Python scripts in order,
45
with comprehensive logging of execution results.
56
"""
@@ -18,23 +19,26 @@
1819
# Ensure the log directory exists
1920
os.makedirs(LOG_DIR, exist_ok=True)
2021

21-
2222
def setup_logging() -> logging.Logger:
23-
"""Configure logging with both file and console handlers.
23+
"""
24+
Configure logging with both file and console handlers.
2425
2526
Returns:
2627
logging.Logger: Configured logger instance
2728
"""
29+
# Create logger
2830
logger = logging.getLogger(__name__)
2931
logger.setLevel(logging.DEBUG)
3032

33+
# Create formatters
3134
file_formatter = logging.Formatter(
3235
'%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
3336
)
3437
console_formatter = logging.Formatter(
3538
'%(asctime)s - %(levelname)s - %(message)s'
3639
)
3740

41+
# Create file handlers
3842
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
3943
debug_handler = logging.FileHandler(
4044
os.path.join(LOG_DIR, f'script_execution_debug_{timestamp}.log')
@@ -48,67 +52,72 @@ def setup_logging() -> logging.Logger:
4852
error_handler.setLevel(logging.ERROR)
4953
error_handler.setFormatter(file_formatter)
5054

55+
# Create console handler
5156
console_handler = logging.StreamHandler()
5257
console_handler.setLevel(logging.INFO)
5358
console_handler.setFormatter(console_formatter)
5459

60+
# Add handlers to logger
5561
logger.addHandler(debug_handler)
5662
logger.addHandler(error_handler)
5763
logger.addHandler(console_handler)
5864

5965
return logger
6066

61-
6267
def run_script(script_name: str, logger: logging.Logger) -> bool:
63-
"""Execute a Python script using the current Python interpreter.
68+
"""
69+
Executes a Python script using the current Python interpreter.
6470
6571
Args:
66-
script_name: The name of the script to run
67-
logger: The logger instance for logging messages
72+
script_name (str): The name of the script to run.
73+
logger (logging.Logger): The logger instance for logging messages.
6874
6975
Returns:
70-
bool: True if the script runs successfully, False otherwise
76+
bool: True if the script runs successfully, False otherwise.
7177
"""
72-
logger.info("Running %s...", script_name)
78+
logger.info(f"Running {script_name}...")
7379

7480
try:
81+
# Run the script using the current Python interpreter
7582
result = subprocess.run(
7683
[sys.executable, script_name],
7784
capture_output=True,
7885
text=True,
7986
check=True
8087
)
81-
logger.info("%s completed successfully.", script_name)
82-
logger.debug("Output:\n%s", result.stdout)
88+
logger.info(f"{script_name} completed successfully.")
89+
logger.debug(f"Output:\n{result.stdout}")
8390
return True
84-
except subprocess.CalledProcessError as error:
85-
logger.error("Error running %s:", script_name)
86-
logger.error(error.stderr)
91+
except subprocess.CalledProcessError as e:
92+
logger.error(f"Error running {script_name}:")
93+
logger.error(e.stderr) # Log the error message if the script fails
8794
return False
8895

89-
90-
def main() -> None:
91-
"""Run a list of Python scripts sequentially.
96+
def main():
97+
"""
98+
Main function to run a list of Python scripts sequentially.
9299
93100
The function will stop execution if any script fails, preventing subsequent
94101
scripts from running if an error is encountered.
95102
"""
96103
logger = setup_logging()
97104

105+
# List of scripts to execute in order
98106
scripts: List[str] = [
99107
"netbox_export.py",
100108
"network_scan.py",
101109
"scan_processor.py",
102110
"netbox_import.py"
103111
]
104112

113+
# Iterate over the list of scripts and run each one
105114
for script in scripts:
106115
if not run_script(script, logger):
107-
logger.error("Execution stopped due to an error in %s", script)
108-
sys.exit(1)
109-
110-
logger.info("All scripts executed successfully.")
111-
116+
logger.error(f"Execution stopped due to an error in {script}")
117+
break # Stop execution if a script fails
118+
else:
119+
logger.info("All scripts executed successfully.")
112120

113121
if __name__ == "__main__":
122+
# Run the main function if the script is executed directly
114123
main()

0 commit comments

Comments
 (0)