autoreload.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. import itertools
  2. import logging
  3. import os
  4. import signal
  5. import subprocess
  6. import sys
  7. import threading
  8. import time
  9. import traceback
  10. import weakref
  11. from collections import defaultdict
  12. from functools import lru_cache, wraps
  13. from pathlib import Path
  14. from types import ModuleType
  15. from zipimport import zipimporter
  16. import django
  17. from django.apps import apps
  18. from django.core.signals import request_finished
  19. from django.dispatch import Signal
  20. from django.utils.functional import cached_property
  21. from django.utils.version import get_version_tuple
  22. autoreload_started = Signal()
  23. file_changed = Signal()
  24. DJANGO_AUTORELOAD_ENV = "RUN_MAIN"
  25. logger = logging.getLogger("django.utils.autoreload")
  26. # If an error is raised while importing a file, it's not placed in sys.modules.
  27. # This means that any future modifications aren't caught. Keep a list of these
  28. # file paths to allow watching them in the future.
  29. _error_files = []
  30. _exception = None
  31. # Exception raised while loading the URLConf.
  32. _url_module_exception = None
  33. try:
  34. import termios
  35. except ImportError:
  36. termios = None
  37. try:
  38. import pywatchman
  39. except ImportError:
  40. pywatchman = None
  41. def is_django_module(module):
  42. """Return True if the given module is nested under Django."""
  43. return module.__name__.startswith("django.")
  44. def is_django_path(path):
  45. """Return True if the given file path is nested under Django."""
  46. return Path(django.__file__).parent in Path(path).parents
  47. def check_errors(fn):
  48. @wraps(fn)
  49. def wrapper(*args, **kwargs):
  50. global _exception
  51. try:
  52. fn(*args, **kwargs)
  53. except Exception as e:
  54. _exception = sys.exc_info()
  55. et, ev, tb = _exception
  56. if getattr(ev, "filename", None) is None:
  57. # get the filename from the last item in the stack
  58. filename = traceback.extract_tb(tb)[-1][0]
  59. else:
  60. filename = ev.filename
  61. if filename not in _error_files:
  62. _error_files.append(filename)
  63. if _url_module_exception is not None:
  64. raise e from _url_module_exception
  65. raise e
  66. return wrapper
  67. def raise_last_exception():
  68. if _exception is not None:
  69. raise _exception[1]
  70. def ensure_echo_on():
  71. """
  72. Ensure that echo mode is enabled. Some tools such as PDB disable
  73. it which causes usability issues after reload.
  74. """
  75. if not termios or not sys.stdin.isatty():
  76. return
  77. attr_list = termios.tcgetattr(sys.stdin)
  78. if not attr_list[3] & termios.ECHO:
  79. attr_list[3] |= termios.ECHO
  80. if hasattr(signal, "SIGTTOU"):
  81. old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
  82. else:
  83. old_handler = None
  84. termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list)
  85. if old_handler is not None:
  86. signal.signal(signal.SIGTTOU, old_handler)
  87. def iter_all_python_module_files():
  88. # This is a hot path during reloading. Create a stable sorted list of
  89. # modules based on the module name and pass it to iter_modules_and_files().
  90. # This ensures cached results are returned in the usual case that modules
  91. # aren't loaded on the fly.
  92. keys = sorted(sys.modules)
  93. modules = tuple(
  94. m
  95. for m in map(sys.modules.__getitem__, keys)
  96. if not isinstance(m, weakref.ProxyTypes)
  97. )
  98. return iter_modules_and_files(modules, frozenset(_error_files))
  99. @lru_cache(maxsize=1)
  100. def iter_modules_and_files(modules, extra_files):
  101. """Iterate through all modules needed to be watched."""
  102. sys_file_paths = []
  103. for module in modules:
  104. # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects
  105. # are added to sys.modules, however they are types not modules and so
  106. # cause issues here.
  107. if not isinstance(module, ModuleType):
  108. continue
  109. if module.__name__ in ("__main__", "__mp_main__"):
  110. # __main__ (usually manage.py) doesn't always have a __spec__ set.
  111. # Handle this by falling back to using __file__, resolved below.
  112. # See https://docs.python.org/reference/import.html#main-spec
  113. # __file__ may not exists, e.g. when running ipdb debugger.
  114. if hasattr(module, "__file__"):
  115. sys_file_paths.append(module.__file__)
  116. continue
  117. if getattr(module, "__spec__", None) is None:
  118. continue
  119. spec = module.__spec__
  120. # Modules could be loaded from places without a concrete location. If
  121. # this is the case, skip them.
  122. if spec.has_location:
  123. origin = (
  124. spec.loader.archive
  125. if isinstance(spec.loader, zipimporter)
  126. else spec.origin
  127. )
  128. sys_file_paths.append(origin)
  129. results = set()
  130. for filename in itertools.chain(sys_file_paths, extra_files):
  131. if not filename:
  132. continue
  133. path = Path(filename)
  134. try:
  135. if not path.exists():
  136. # The module could have been removed, don't fail loudly if this
  137. # is the case.
  138. continue
  139. except ValueError as e:
  140. # Network filesystems may return null bytes in file paths.
  141. logger.debug('"%s" raised when resolving path: "%s"', e, path)
  142. continue
  143. resolved_path = path.resolve().absolute()
  144. results.add(resolved_path)
  145. return frozenset(results)
  146. @lru_cache(maxsize=1)
  147. def common_roots(paths):
  148. """
  149. Return a tuple of common roots that are shared between the given paths.
  150. File system watchers operate on directories and aren't cheap to create.
  151. Try to find the minimum set of directories to watch that encompass all of
  152. the files that need to be watched.
  153. """
  154. # Inspired from Werkzeug:
  155. # https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py
  156. # Create a sorted list of the path components, longest first.
  157. path_parts = sorted([x.parts for x in paths], key=len, reverse=True)
  158. tree = {}
  159. for chunks in path_parts:
  160. node = tree
  161. # Add each part of the path to the tree.
  162. for chunk in chunks:
  163. node = node.setdefault(chunk, {})
  164. # Clear the last leaf in the tree.
  165. node.clear()
  166. # Turn the tree into a list of Path instances.
  167. def _walk(node, path):
  168. for prefix, child in node.items():
  169. yield from _walk(child, [*path, prefix])
  170. if not node:
  171. yield Path(*path)
  172. return tuple(_walk(tree, ()))
  173. def sys_path_directories():
  174. """
  175. Yield absolute directories from sys.path, ignoring entries that don't
  176. exist.
  177. """
  178. for path in sys.path:
  179. path = Path(path)
  180. if not path.exists():
  181. continue
  182. resolved_path = path.resolve().absolute()
  183. # If the path is a file (like a zip file), watch the parent directory.
  184. if resolved_path.is_file():
  185. yield resolved_path.parent
  186. else:
  187. yield resolved_path
  188. def get_child_arguments():
  189. """
  190. Return the executable. This contains a workaround for Windows if the
  191. executable is reported to not have the .exe extension which can cause bugs
  192. on reloading.
  193. """
  194. import __main__
  195. py_script = Path(sys.argv[0])
  196. exe_entrypoint = py_script.with_suffix(".exe")
  197. args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions]
  198. if sys.implementation.name in ("cpython", "pypy"):
  199. args.extend(
  200. f"-X{key}" if value is True else f"-X{key}={value}"
  201. for key, value in sys._xoptions.items()
  202. )
  203. # __spec__ is set when the server was started with the `-m` option,
  204. # see https://docs.python.org/3/reference/import.html#main-spec
  205. # __spec__ may not exist, e.g. when running in a Conda env.
  206. if getattr(__main__, "__spec__", None) is not None and not exe_entrypoint.exists():
  207. spec = __main__.__spec__
  208. if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent:
  209. name = spec.parent
  210. else:
  211. name = spec.name
  212. args += ["-m", name]
  213. args += sys.argv[1:]
  214. elif not py_script.exists():
  215. # sys.argv[0] may not exist for several reasons on Windows.
  216. # It may exist with a .exe extension or have a -script.py suffix.
  217. if exe_entrypoint.exists():
  218. # Should be executed directly, ignoring sys.executable.
  219. return [exe_entrypoint, *sys.argv[1:]]
  220. script_entrypoint = py_script.with_name("%s-script.py" % py_script.name)
  221. if script_entrypoint.exists():
  222. # Should be executed as usual.
  223. return [*args, script_entrypoint, *sys.argv[1:]]
  224. raise RuntimeError("Script %s does not exist." % py_script)
  225. else:
  226. args += sys.argv
  227. return args
  228. def trigger_reload(filename):
  229. logger.info("%s changed, reloading.", filename)
  230. sys.exit(3)
  231. def restart_with_reloader():
  232. new_environ = {**os.environ, DJANGO_AUTORELOAD_ENV: "true"}
  233. orig = getattr(sys, "orig_argv", ())
  234. if any(
  235. (arg == "-u")
  236. or (
  237. arg.startswith("-")
  238. and not arg.startswith(("--", "-X", "-W"))
  239. and len(arg) > 2
  240. and arg[1:].isalpha()
  241. and "u" in arg
  242. )
  243. for arg in orig[1:]
  244. ):
  245. new_environ.setdefault("PYTHONUNBUFFERED", "1")
  246. args = get_child_arguments()
  247. while True:
  248. p = subprocess.run(args, env=new_environ, close_fds=False)
  249. if p.returncode != 3:
  250. return p.returncode
  251. class BaseReloader:
  252. def __init__(self):
  253. self.extra_files = set()
  254. self.directory_globs = defaultdict(set)
  255. self._stop_condition = threading.Event()
  256. def watch_dir(self, path, glob):
  257. path = Path(path)
  258. try:
  259. path = path.absolute()
  260. except FileNotFoundError:
  261. logger.debug(
  262. "Unable to watch directory %s as it cannot be resolved.",
  263. path,
  264. exc_info=True,
  265. )
  266. return
  267. logger.debug("Watching dir %s with glob %s.", path, glob)
  268. self.directory_globs[path].add(glob)
  269. def watched_files(self, include_globs=True):
  270. """
  271. Yield all files that need to be watched, including module files and
  272. files within globs.
  273. """
  274. yield from iter_all_python_module_files()
  275. yield from self.extra_files
  276. if include_globs:
  277. for directory, patterns in self.directory_globs.items():
  278. for pattern in patterns:
  279. yield from directory.glob(pattern)
  280. def wait_for_apps_ready(self, app_reg, django_main_thread):
  281. """
  282. Wait until Django reports that the apps have been loaded. If the given
  283. thread has terminated before the apps are ready, then a SyntaxError or
  284. other non-recoverable error has been raised. In that case, stop waiting
  285. for the apps_ready event and continue processing.
  286. Return True if the thread is alive and the ready event has been
  287. triggered, or False if the thread is terminated while waiting for the
  288. event.
  289. """
  290. while django_main_thread.is_alive():
  291. if app_reg.ready_event.wait(timeout=0.1):
  292. return True
  293. else:
  294. logger.debug("Main Django thread has terminated before apps are ready.")
  295. return False
  296. def run(self, django_main_thread):
  297. global _url_module_exception
  298. logger.debug("Waiting for apps ready_event.")
  299. self.wait_for_apps_ready(apps, django_main_thread)
  300. from django.urls import get_resolver
  301. # Prevent a race condition where URL modules aren't loaded when the
  302. # reloader starts by accessing the urlconf_module property.
  303. try:
  304. get_resolver().urlconf_module
  305. except Exception as e:
  306. # Loading the urlconf can result in errors during development.
  307. # If this occurs then store the error and continue.
  308. _url_module_exception = e
  309. logger.debug("Apps ready_event triggered. Sending autoreload_started signal.")
  310. autoreload_started.send(sender=self)
  311. self.run_loop()
  312. def run_loop(self):
  313. ticker = self.tick()
  314. while not self.should_stop:
  315. try:
  316. next(ticker)
  317. except StopIteration:
  318. break
  319. self.stop()
  320. def tick(self):
  321. """
  322. This generator is called in a loop from run_loop. It's important that
  323. the method takes care of pausing or otherwise waiting for a period of
  324. time. This split between run_loop() and tick() is to improve the
  325. testability of the reloader implementations by decoupling the work they
  326. do from the loop.
  327. """
  328. raise NotImplementedError("subclasses must implement tick().")
  329. @classmethod
  330. def check_availability(cls):
  331. raise NotImplementedError("subclasses must implement check_availability().")
  332. def notify_file_changed(self, path):
  333. results = file_changed.send(sender=self, file_path=path)
  334. logger.debug("%s notified as changed. Signal results: %s.", path, results)
  335. if not any(res[1] for res in results):
  336. trigger_reload(path)
  337. # These are primarily used for testing.
  338. @property
  339. def should_stop(self):
  340. return self._stop_condition.is_set()
  341. def stop(self):
  342. self._stop_condition.set()
  343. class StatReloader(BaseReloader):
  344. SLEEP_TIME = 1 # Check for changes once per second.
  345. def tick(self):
  346. mtimes = {}
  347. while True:
  348. for filepath, mtime in self.snapshot_files():
  349. old_time = mtimes.get(filepath)
  350. mtimes[filepath] = mtime
  351. if old_time is None:
  352. logger.debug("File %s first seen with mtime %s", filepath, mtime)
  353. continue
  354. elif mtime > old_time:
  355. logger.debug(
  356. "File %s previous mtime: %s, current mtime: %s",
  357. filepath,
  358. old_time,
  359. mtime,
  360. )
  361. self.notify_file_changed(filepath)
  362. time.sleep(self.SLEEP_TIME)
  363. yield
  364. def snapshot_files(self):
  365. # watched_files may produce duplicate paths if globs overlap.
  366. seen_files = set()
  367. for file in self.watched_files():
  368. if file in seen_files:
  369. continue
  370. try:
  371. mtime = file.stat().st_mtime
  372. except OSError:
  373. # This is thrown when the file does not exist.
  374. continue
  375. seen_files.add(file)
  376. yield file, mtime
  377. @classmethod
  378. def check_availability(cls):
  379. return True
  380. class WatchmanUnavailable(RuntimeError):
  381. pass
  382. class WatchmanReloader(BaseReloader):
  383. def __init__(self):
  384. self.roots = defaultdict(set)
  385. self.processed_request = threading.Event()
  386. self.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 5))
  387. super().__init__()
  388. @cached_property
  389. def client(self):
  390. return pywatchman.client(timeout=self.client_timeout)
  391. def _watch_root(self, root):
  392. # In practice this shouldn't occur, however, it's possible that a
  393. # directory that doesn't exist yet is being watched. If it's outside of
  394. # sys.path then this will end up a new root. How to handle this isn't
  395. # clear: Not adding the root will likely break when subscribing to the
  396. # changes, however, as this is currently an internal API, no files
  397. # will be being watched outside of sys.path. Fixing this by checking
  398. # inside watch_glob() and watch_dir() is expensive, instead this could
  399. # fall back to the StatReloader if this case is detected? For
  400. # now, watching its parent, if possible, is sufficient.
  401. if not root.exists():
  402. if not root.parent.exists():
  403. logger.warning(
  404. "Unable to watch root dir %s as neither it or its parent exist.",
  405. root,
  406. )
  407. return
  408. root = root.parent
  409. result = self.client.query("watch-project", str(root.absolute()))
  410. if "warning" in result:
  411. logger.warning("Watchman warning: %s", result["warning"])
  412. logger.debug("Watchman watch-project result: %s", result)
  413. return result["watch"], result.get("relative_path")
  414. @lru_cache
  415. def _get_clock(self, root):
  416. return self.client.query("clock", root)["clock"]
  417. def _subscribe(self, directory, name, expression):
  418. root, rel_path = self._watch_root(directory)
  419. # Only receive notifications of files changing, filtering out other
  420. # types like special files:
  421. # https://facebook.github.io/watchman/docs/type
  422. only_files_expression = [
  423. "allof",
  424. ["anyof", ["type", "f"], ["type", "l"]],
  425. expression,
  426. ]
  427. query = {
  428. "expression": only_files_expression,
  429. "fields": ["name"],
  430. "since": self._get_clock(root),
  431. "dedup_results": True,
  432. }
  433. if rel_path:
  434. query["relative_root"] = rel_path
  435. logger.debug(
  436. "Issuing watchman subscription %s, for root %s. Query: %s",
  437. name,
  438. root,
  439. query,
  440. )
  441. self.client.query("subscribe", root, name, query)
  442. def _subscribe_dir(self, directory, filenames):
  443. if not directory.exists():
  444. if not directory.parent.exists():
  445. logger.warning(
  446. "Unable to watch directory %s as neither it or its parent exist.",
  447. directory,
  448. )
  449. return
  450. prefix = "files-parent-%s" % directory.name
  451. filenames = ["%s/%s" % (directory.name, filename) for filename in filenames]
  452. directory = directory.parent
  453. expression = ["name", filenames, "wholename"]
  454. else:
  455. prefix = "files"
  456. expression = ["name", filenames]
  457. self._subscribe(directory, "%s:%s" % (prefix, directory), expression)
  458. def _watch_glob(self, directory, patterns):
  459. """
  460. Watch a directory with a specific glob. If the directory doesn't yet
  461. exist, attempt to watch the parent directory and amend the patterns to
  462. include this. It's important this method isn't called more than once
  463. per directory when updating all subscriptions. Subsequent calls will
  464. overwrite the named subscription, so it must include all possible glob
  465. expressions.
  466. """
  467. prefix = "glob"
  468. if not directory.exists():
  469. if not directory.parent.exists():
  470. logger.warning(
  471. "Unable to watch directory %s as neither it or its parent exist.",
  472. directory,
  473. )
  474. return
  475. prefix = "glob-parent-%s" % directory.name
  476. patterns = ["%s/%s" % (directory.name, pattern) for pattern in patterns]
  477. directory = directory.parent
  478. expression = ["anyof"]
  479. for pattern in patterns:
  480. expression.append(["match", pattern, "wholename"])
  481. self._subscribe(directory, "%s:%s" % (prefix, directory), expression)
  482. def watched_roots(self, watched_files):
  483. extra_directories = self.directory_globs.keys()
  484. watched_file_dirs = [f.parent for f in watched_files]
  485. sys_paths = list(sys_path_directories())
  486. return frozenset((*extra_directories, *watched_file_dirs, *sys_paths))
  487. def _update_watches(self):
  488. watched_files = list(self.watched_files(include_globs=False))
  489. found_roots = common_roots(self.watched_roots(watched_files))
  490. logger.debug("Watching %s files", len(watched_files))
  491. logger.debug("Found common roots: %s", found_roots)
  492. # Setup initial roots for performance, shortest roots first.
  493. for root in sorted(found_roots):
  494. self._watch_root(root)
  495. for directory, patterns in self.directory_globs.items():
  496. self._watch_glob(directory, patterns)
  497. # Group sorted watched_files by their parent directory.
  498. sorted_files = sorted(watched_files, key=lambda p: p.parent)
  499. for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent):
  500. # These paths need to be relative to the parent directory.
  501. self._subscribe_dir(
  502. directory, [str(p.relative_to(directory)) for p in group]
  503. )
  504. def update_watches(self):
  505. try:
  506. self._update_watches()
  507. except Exception as ex:
  508. # If the service is still available, raise the original exception.
  509. if self.check_server_status(ex):
  510. raise
  511. def _check_subscription(self, sub):
  512. subscription = self.client.getSubscription(sub)
  513. if not subscription:
  514. return
  515. logger.debug("Watchman subscription %s has results.", sub)
  516. for result in subscription:
  517. # When using watch-project, it's not simple to get the relative
  518. # directory without storing some specific state. Store the full
  519. # path to the directory in the subscription name, prefixed by its
  520. # type (glob, files).
  521. root_directory = Path(result["subscription"].split(":", 1)[1])
  522. logger.debug("Found root directory %s", root_directory)
  523. for file in result.get("files", []):
  524. self.notify_file_changed(root_directory / file)
  525. def request_processed(self, **kwargs):
  526. logger.debug("Request processed. Setting update_watches event.")
  527. self.processed_request.set()
  528. def tick(self):
  529. request_finished.connect(self.request_processed)
  530. self.update_watches()
  531. while True:
  532. if self.processed_request.is_set():
  533. self.update_watches()
  534. self.processed_request.clear()
  535. try:
  536. self.client.receive()
  537. except pywatchman.SocketTimeout:
  538. pass
  539. except pywatchman.WatchmanError as ex:
  540. logger.debug("Watchman error: %s, checking server status.", ex)
  541. self.check_server_status(ex)
  542. else:
  543. for sub in list(self.client.subs.keys()):
  544. self._check_subscription(sub)
  545. yield
  546. # Protect against busy loops.
  547. time.sleep(0.1)
  548. def stop(self):
  549. self.client.close()
  550. super().stop()
  551. def check_server_status(self, inner_ex=None):
  552. """Return True if the server is available."""
  553. try:
  554. self.client.query("version")
  555. except Exception:
  556. raise WatchmanUnavailable(str(inner_ex)) from inner_ex
  557. return True
  558. @classmethod
  559. def check_availability(cls):
  560. if not pywatchman:
  561. raise WatchmanUnavailable("pywatchman not installed.")
  562. client = pywatchman.client(timeout=0.1)
  563. try:
  564. result = client.capabilityCheck()
  565. except Exception:
  566. # The service is down?
  567. raise WatchmanUnavailable("Cannot connect to the watchman service.")
  568. version = get_version_tuple(result["version"])
  569. # Watchman 4.9 includes multiple improvements to watching project
  570. # directories as well as case insensitive filesystems.
  571. logger.debug("Watchman version %s", version)
  572. if version < (4, 9):
  573. raise WatchmanUnavailable("Watchman 4.9 or later is required.")
  574. def get_reloader():
  575. """Return the most suitable reloader for this environment."""
  576. try:
  577. WatchmanReloader.check_availability()
  578. except WatchmanUnavailable:
  579. return StatReloader()
  580. return WatchmanReloader()
  581. def start_django(reloader, main_func, *args, **kwargs):
  582. ensure_echo_on()
  583. main_func = check_errors(main_func)
  584. django_main_thread = threading.Thread(
  585. target=main_func, args=args, kwargs=kwargs, name="django-main-thread"
  586. )
  587. django_main_thread.daemon = True
  588. django_main_thread.start()
  589. while not reloader.should_stop:
  590. reloader.run(django_main_thread)
  591. def run_with_reloader(main_func, *args, **kwargs):
  592. signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
  593. try:
  594. if os.environ.get(DJANGO_AUTORELOAD_ENV) == "true":
  595. reloader = get_reloader()
  596. logger.info(
  597. "Watching for file changes with %s", reloader.__class__.__name__
  598. )
  599. start_django(reloader, main_func, *args, **kwargs)
  600. else:
  601. exit_code = restart_with_reloader()
  602. sys.exit(exit_code)
  603. except KeyboardInterrupt:
  604. pass