Handle module preloading with configurable error handling. Args: preload: List of module names to preload. main_path: Path to __main__ module if '__main__' is in preload. sys_path: sys.path to use for imports (None means use current). sys_argv: sys.argv to use (N
(preload, main_path=None, sys_path=None, sys_argv=None,
on_error='ignore')
| 245 | |
| 246 | |
| 247 | def _handle_preload(preload, main_path=None, sys_path=None, sys_argv=None, |
| 248 | on_error='ignore'): |
| 249 | """Handle module preloading with configurable error handling. |
| 250 | |
| 251 | Args: |
| 252 | preload: List of module names to preload. |
| 253 | main_path: Path to __main__ module if '__main__' is in preload. |
| 254 | sys_path: sys.path to use for imports (None means use current). |
| 255 | sys_argv: sys.argv to use (None means use current). |
| 256 | on_error: How to handle import errors ("ignore", "warn", or "fail"). |
| 257 | """ |
| 258 | if not preload: |
| 259 | return |
| 260 | |
| 261 | if sys_argv is not None: |
| 262 | sys.argv[:] = sys_argv |
| 263 | if sys_path is not None: |
| 264 | sys.path[:] = sys_path |
| 265 | |
| 266 | if '__main__' in preload and main_path is not None: |
| 267 | process.current_process()._inheriting = True |
| 268 | try: |
| 269 | spawn.import_main_path(main_path) |
| 270 | except Exception as e: |
| 271 | # Catch broad Exception because import_main_path() uses |
| 272 | # runpy.run_path() which executes the script and can raise |
| 273 | # any exception, not just ImportError |
| 274 | _handle_import_error( |
| 275 | on_error, f"__main__ from {main_path!r}", e, warn_stacklevel=2 |
| 276 | ) |
| 277 | finally: |
| 278 | del process.current_process()._inheriting |
| 279 | |
| 280 | for modname in preload: |
| 281 | try: |
| 282 | __import__(modname) |
| 283 | except ImportError as e: |
| 284 | _handle_import_error( |
| 285 | on_error, f"module {modname!r}", e, warn_stacklevel=2 |
| 286 | ) |
| 287 | |
| 288 | # gh-135335: flush stdout/stderr in case any of the preloaded modules |
| 289 | # wrote to them, otherwise children might inherit buffered data |
| 290 | util._flush_std_streams() |
| 291 | |
| 292 | |
| 293 | def main(listener_fd, alive_r, preload, main_path=None, sys_path=None, |
no test coverage detected
searching dependent graphs…