Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is simi
()
| 268 | |
| 269 | |
| 270 | def main() -> None: |
| 271 | """Command-line wrapper to re-run a script whenever its source changes. |
| 272 | |
| 273 | Scripts may be specified by filename or module name:: |
| 274 | |
| 275 | python -m tornado.autoreload -m tornado.test.runtests |
| 276 | python -m tornado.autoreload tornado/test/runtests.py |
| 277 | |
| 278 | Running a script with this wrapper is similar to calling |
| 279 | `tornado.autoreload.wait` at the end of the script, but this wrapper |
| 280 | can catch import-time problems like syntax errors that would otherwise |
| 281 | prevent the script from reaching its call to `wait`. |
| 282 | """ |
| 283 | # Remember that we were launched with autoreload as main. |
| 284 | # The main module can be tricky; set the variables both in our globals |
| 285 | # (which may be __main__) and the real importable version. |
| 286 | import tornado.autoreload |
| 287 | |
| 288 | global _autoreload_is_main |
| 289 | global _original_argv, _original_spec |
| 290 | tornado.autoreload._autoreload_is_main = _autoreload_is_main = True |
| 291 | original_argv = sys.argv |
| 292 | tornado.autoreload._original_argv = _original_argv = original_argv |
| 293 | original_spec = getattr(sys.modules["__main__"], "__spec__", None) |
| 294 | tornado.autoreload._original_spec = _original_spec = original_spec |
| 295 | sys.argv = sys.argv[:] |
| 296 | if len(sys.argv) >= 3 and sys.argv[1] == "-m": |
| 297 | mode = "module" |
| 298 | module = sys.argv[2] |
| 299 | del sys.argv[1:3] |
| 300 | elif len(sys.argv) >= 2: |
| 301 | mode = "script" |
| 302 | script = sys.argv[1] |
| 303 | sys.argv = sys.argv[1:] |
| 304 | else: |
| 305 | print(_USAGE, file=sys.stderr) |
| 306 | sys.exit(1) |
| 307 | |
| 308 | try: |
| 309 | if mode == "module": |
| 310 | import runpy |
| 311 | |
| 312 | runpy.run_module(module, run_name="__main__", alter_sys=True) |
| 313 | elif mode == "script": |
| 314 | with open(script) as f: |
| 315 | # Execute the script in our namespace instead of creating |
| 316 | # a new one so that something that tries to import __main__ |
| 317 | # (e.g. the unittest module) will see names defined in the |
| 318 | # script instead of just those defined in this module. |
| 319 | global __file__ |
| 320 | __file__ = script |
| 321 | # If __package__ is defined, imports may be incorrectly |
| 322 | # interpreted as relative to this module. |
| 323 | global __package__ |
| 324 | del __package__ |
| 325 | exec_in(f.read(), globals(), globals()) |
| 326 | except SystemExit as e: |
| 327 | gen_log.info("Script exited with status %s", e.code) |