Skip to content

Commit 176ed52

Browse files
authored
Update main.py
1 parent 0cff3ac commit 176ed52

File tree

1 file changed

+27
-29
lines changed

1 file changed

+27
-29
lines changed

main.py

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
"""Script runner that executes multiple Python scripts in sequence.
2+
3+
This module provides functionality to run multiple Python scripts in order,
4+
with comprehensive logging of execution results.
5+
"""
6+
17
import subprocess
28
import sys
39
import os
@@ -12,26 +18,23 @@
1218
# Ensure the log directory exists
1319
os.makedirs(LOG_DIR, exist_ok=True)
1420

21+
1522
def setup_logging() -> logging.Logger:
16-
"""
17-
Configure logging with both file and console handlers.
23+
"""Configure logging with both file and console handlers.
1824
1925
Returns:
2026
logging.Logger: Configured logger instance
2127
"""
22-
# Create logger
2328
logger = logging.getLogger(__name__)
2429
logger.setLevel(logging.DEBUG)
2530

26-
# Create formatters
2731
file_formatter = logging.Formatter(
2832
'%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
2933
)
3034
console_formatter = logging.Formatter(
3135
'%(asctime)s - %(levelname)s - %(message)s'
3236
)
3337

34-
# Create file handlers
3538
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
3639
debug_handler = logging.FileHandler(
3740
os.path.join(LOG_DIR, f'script_execution_debug_{timestamp}.log')
@@ -45,72 +48,67 @@ def setup_logging() -> logging.Logger:
4548
error_handler.setLevel(logging.ERROR)
4649
error_handler.setFormatter(file_formatter)
4750

48-
# Create console handler
4951
console_handler = logging.StreamHandler()
5052
console_handler.setLevel(logging.INFO)
5153
console_handler.setFormatter(console_formatter)
5254

53-
# Add handlers to logger
5455
logger.addHandler(debug_handler)
5556
logger.addHandler(error_handler)
5657
logger.addHandler(console_handler)
5758

5859
return logger
5960

61+
6062
def run_script(script_name: str, logger: logging.Logger) -> bool:
61-
"""
62-
Executes a Python script using the current Python interpreter.
63+
"""Execute a Python script using the current Python interpreter.
6364
6465
Args:
65-
script_name (str): The name of the script to run.
66-
logger (logging.Logger): The logger instance for logging messages.
66+
script_name: The name of the script to run
67+
logger: The logger instance for logging messages
6768
6869
Returns:
69-
bool: True if the script runs successfully, False otherwise.
70+
bool: True if the script runs successfully, False otherwise
7071
"""
71-
logger.info(f"Running {script_name}...")
72+
logger.info("Running %s...", script_name)
7273

7374
try:
74-
# Run the script using the current Python interpreter
7575
result = subprocess.run(
7676
[sys.executable, script_name],
7777
capture_output=True,
7878
text=True,
7979
check=True
8080
)
81-
logger.info(f"{script_name} completed successfully.")
82-
logger.debug(f"Output:\n{result.stdout}")
81+
logger.info("%s completed successfully.", script_name)
82+
logger.debug("Output:\n%s", result.stdout)
8383
return True
84-
except subprocess.CalledProcessError as e:
85-
logger.error(f"Error running {script_name}:")
86-
logger.error(e.stderr) # Log the error message if the script fails
84+
except subprocess.CalledProcessError as error:
85+
logger.error("Error running %s:", script_name)
86+
logger.error(error.stderr)
8787
return False
8888

89-
def main():
90-
"""
91-
Main function to run a list of Python scripts sequentially.
89+
90+
def main() -> None:
91+
"""Run a list of Python scripts sequentially.
9292
9393
The function will stop execution if any script fails, preventing subsequent
9494
scripts from running if an error is encountered.
9595
"""
9696
logger = setup_logging()
9797

98-
# List of scripts to execute in order
9998
scripts: List[str] = [
10099
"netbox_export.py",
101100
"network_scan.py",
102101
"scan_processor.py",
103102
"netbox_import.py"
104103
]
105104

106-
# Iterate over the list of scripts and run each one
107105
for script in scripts:
108106
if not run_script(script, logger):
109-
logger.error(f"Execution stopped due to an error in {script}")
110-
break # Stop execution if a script fails
111-
else:
112-
logger.info("All scripts executed successfully.")
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+
113112

114113
if __name__ == "__main__":
115-
# Run the main function if the script is executed directly
116114
main()

0 commit comments

Comments
 (0)