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