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
+
1
7
import subprocess
2
8
import sys
3
9
import os
12
18
# Ensure the log directory exists
13
19
os .makedirs (LOG_DIR , exist_ok = True )
14
20
21
+
15
22
def setup_logging () -> logging .Logger :
16
- """
17
- Configure logging with both file and console handlers.
23
+ """Configure logging with both file and console handlers.
18
24
19
25
Returns:
20
26
logging.Logger: Configured logger instance
21
27
"""
22
- # Create logger
23
28
logger = logging .getLogger (__name__ )
24
29
logger .setLevel (logging .DEBUG )
25
30
26
- # Create formatters
27
31
file_formatter = logging .Formatter (
28
32
'%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
29
33
)
30
34
console_formatter = logging .Formatter (
31
35
'%(asctime)s - %(levelname)s - %(message)s'
32
36
)
33
37
34
- # Create file handlers
35
38
timestamp = datetime .now ().strftime ('%Y%m%d_%H%M%S' )
36
39
debug_handler = logging .FileHandler (
37
40
os .path .join (LOG_DIR , f'script_execution_debug_{ timestamp } .log' )
@@ -45,72 +48,67 @@ def setup_logging() -> logging.Logger:
45
48
error_handler .setLevel (logging .ERROR )
46
49
error_handler .setFormatter (file_formatter )
47
50
48
- # Create console handler
49
51
console_handler = logging .StreamHandler ()
50
52
console_handler .setLevel (logging .INFO )
51
53
console_handler .setFormatter (console_formatter )
52
54
53
- # Add handlers to logger
54
55
logger .addHandler (debug_handler )
55
56
logger .addHandler (error_handler )
56
57
logger .addHandler (console_handler )
57
58
58
59
return logger
59
60
61
+
60
62
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.
63
64
64
65
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
67
68
68
69
Returns:
69
- bool: True if the script runs successfully, False otherwise.
70
+ bool: True if the script runs successfully, False otherwise
70
71
"""
71
- logger .info (f "Running { script_name } ..." )
72
+ logger .info ("Running %s ..." , script_name )
72
73
73
74
try :
74
- # Run the script using the current Python interpreter
75
75
result = subprocess .run (
76
76
[sys .executable , script_name ],
77
77
capture_output = True ,
78
78
text = True ,
79
79
check = True
80
80
)
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 )
83
83
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 )
87
87
return False
88
88
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.
92
92
93
93
The function will stop execution if any script fails, preventing subsequent
94
94
scripts from running if an error is encountered.
95
95
"""
96
96
logger = setup_logging ()
97
97
98
- # List of scripts to execute in order
99
98
scripts : List [str ] = [
100
99
"netbox_export.py" ,
101
100
"network_scan.py" ,
102
101
"scan_processor.py" ,
103
102
"netbox_import.py"
104
103
]
105
104
106
- # Iterate over the list of scripts and run each one
107
105
for script in scripts :
108
106
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
+
113
112
114
113
if __name__ == "__main__" :
115
- # Run the main function if the script is executed directly
116
114
main ()
0 commit comments