run.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import contextlib
  2. import json
  3. import logging
  4. import os
  5. import re
  6. import shlex
  7. import signal
  8. import subprocess
  9. import sys
  10. from collections.abc import Callable, Generator
  11. from importlib import import_module
  12. from multiprocessing import get_context
  13. from multiprocessing.context import SpawnProcess
  14. from pathlib import Path
  15. from time import sleep
  16. from typing import TYPE_CHECKING, Any
  17. import anyio
  18. from .filters import DefaultFilter
  19. from .main import Change, FileChange, awatch, watch
  20. if TYPE_CHECKING:
  21. from typing import Literal
  22. __all__ = 'run_process', 'arun_process', 'detect_target_type', 'import_string'
  23. logger = logging.getLogger('watchfiles.main')
  24. def run_process(
  25. *paths: Path | str,
  26. target: str | Callable[..., Any],
  27. args: tuple[Any, ...] = (),
  28. kwargs: dict[str, Any] | None = None,
  29. target_type: "Literal['function', 'command', 'auto']" = 'auto',
  30. callback: Callable[[set[FileChange]], None] | None = None,
  31. watch_filter: Callable[[Change, str], bool] | None = DefaultFilter(),
  32. grace_period: float = 0,
  33. debounce: int = 1_600,
  34. step: int = 50,
  35. debug: bool | None = None,
  36. sigint_timeout: int = 5,
  37. sigkill_timeout: int = 1,
  38. recursive: bool = True,
  39. ignore_permission_denied: bool = False,
  40. ) -> int:
  41. """
  42. Run a process and restart it upon file changes.
  43. `run_process` can work in two ways:
  44. * Using `multiprocessing.Process` † to run a python function
  45. * Or, using `subprocess.Popen` to run a command
  46. !!! note
  47. **†** technically `multiprocessing.get_context('spawn').Process` to avoid forking and improve
  48. code reload/import.
  49. Internally, `run_process` uses [`watch`][watchfiles.watch] with `raise_interrupt=False` so the function
  50. exits cleanly upon `Ctrl+C`.
  51. Args:
  52. *paths: matches the same argument of [`watch`][watchfiles.watch]
  53. target: function or command to run
  54. args: arguments to pass to `target`, only used if `target` is a function
  55. kwargs: keyword arguments to pass to `target`, only used if `target` is a function
  56. target_type: type of target. Can be `'function'`, `'command'`, or `'auto'` in which case
  57. [`detect_target_type`][watchfiles.run.detect_target_type] is used to determine the type.
  58. callback: function to call on each reload, the function should accept a set of changes as the sole argument
  59. watch_filter: matches the same argument of [`watch`][watchfiles.watch]
  60. grace_period: number of seconds after the process is started before watching for changes
  61. debounce: matches the same argument of [`watch`][watchfiles.watch]
  62. step: matches the same argument of [`watch`][watchfiles.watch]
  63. debug: matches the same argument of [`watch`][watchfiles.watch]
  64. sigint_timeout: the number of seconds to wait after sending sigint before sending sigkill
  65. sigkill_timeout: the number of seconds to wait after sending sigkill before raising an exception
  66. recursive: matches the same argument of [`watch`][watchfiles.watch]
  67. Returns:
  68. number of times the function was reloaded.
  69. ```py title="Example of run_process running a function"
  70. from watchfiles import run_process
  71. def callback(changes):
  72. print('changes detected:', changes)
  73. def foobar(a, b):
  74. print('foobar called with:', a, b)
  75. if __name__ == '__main__':
  76. run_process('./path/to/dir', target=foobar, args=(1, 2), callback=callback)
  77. ```
  78. As well as using a `callback` function, changes can be accessed from within the target function,
  79. using the `WATCHFILES_CHANGES` environment variable.
  80. ```py title="Example of run_process accessing changes"
  81. from watchfiles import run_process
  82. def foobar(a, b, c):
  83. # changes will be an empty list "[]" the first time the function is called
  84. changes = os.getenv('WATCHFILES_CHANGES')
  85. changes = json.loads(changes)
  86. print('foobar called due to changes:', changes)
  87. if __name__ == '__main__':
  88. run_process('./path/to/dir', target=foobar, args=(1, 2, 3))
  89. ```
  90. Again with the target as `command`, `WATCHFILES_CHANGES` can be used
  91. to access changes.
  92. ```bash title="example.sh"
  93. echo "changers: ${WATCHFILES_CHANGES}"
  94. ```
  95. ```py title="Example of run_process running a command"
  96. from watchfiles import run_process
  97. if __name__ == '__main__':
  98. run_process('.', target='./example.sh')
  99. ```
  100. """
  101. if target_type == 'auto':
  102. target_type = detect_target_type(target)
  103. logger.debug('running "%s" as %s', target, target_type)
  104. catch_sigterm()
  105. process = start_process(target, target_type, args, kwargs)
  106. reloads = 0
  107. if grace_period:
  108. logger.debug('sleeping for %s seconds before watching for changes', grace_period)
  109. sleep(grace_period)
  110. try:
  111. for changes in watch(
  112. *paths,
  113. watch_filter=watch_filter,
  114. debounce=debounce,
  115. step=step,
  116. debug=debug,
  117. raise_interrupt=False,
  118. recursive=recursive,
  119. ignore_permission_denied=ignore_permission_denied,
  120. ):
  121. callback and callback(changes)
  122. process.stop(sigint_timeout=sigint_timeout, sigkill_timeout=sigkill_timeout)
  123. process = start_process(target, target_type, args, kwargs, changes)
  124. reloads += 1
  125. finally:
  126. process.stop()
  127. return reloads
  128. async def arun_process(
  129. *paths: Path | str,
  130. target: str | Callable[..., Any],
  131. args: tuple[Any, ...] = (),
  132. kwargs: dict[str, Any] | None = None,
  133. target_type: "Literal['function', 'command', 'auto']" = 'auto',
  134. callback: Callable[[set[FileChange]], Any] | None = None,
  135. watch_filter: Callable[[Change, str], bool] | None = DefaultFilter(),
  136. grace_period: float = 0,
  137. debounce: int = 1_600,
  138. step: int = 50,
  139. debug: bool | None = None,
  140. recursive: bool = True,
  141. ignore_permission_denied: bool = False,
  142. ) -> int:
  143. """
  144. Async equivalent of [`run_process`][watchfiles.run_process], all arguments match those of `run_process` except
  145. `callback` which can be a coroutine.
  146. Starting and stopping the process and watching for changes is done in a separate thread.
  147. As with `run_process`, internally `arun_process` uses [`awatch`][watchfiles.awatch], however `KeyboardInterrupt`
  148. cannot be caught and suppressed in `awatch` so these errors need to be caught separately, see below.
  149. ```py title="Example of arun_process usage"
  150. import asyncio
  151. from watchfiles import arun_process
  152. async def callback(changes):
  153. await asyncio.sleep(0.1)
  154. print('changes detected:', changes)
  155. def foobar(a, b):
  156. print('foobar called with:', a, b)
  157. async def main():
  158. await arun_process('.', target=foobar, args=(1, 2), callback=callback)
  159. if __name__ == '__main__':
  160. try:
  161. asyncio.run(main())
  162. except KeyboardInterrupt:
  163. print('stopped via KeyboardInterrupt')
  164. ```
  165. """
  166. import inspect
  167. if target_type == 'auto':
  168. target_type = detect_target_type(target)
  169. logger.debug('running "%s" as %s', target, target_type)
  170. catch_sigterm()
  171. process = await anyio.to_thread.run_sync(start_process, target, target_type, args, kwargs)
  172. reloads = 0
  173. if grace_period:
  174. logger.debug('sleeping for %s seconds before watching for changes', grace_period)
  175. await anyio.sleep(grace_period)
  176. async for changes in awatch(
  177. *paths,
  178. watch_filter=watch_filter,
  179. debounce=debounce,
  180. step=step,
  181. debug=debug,
  182. recursive=recursive,
  183. ignore_permission_denied=ignore_permission_denied,
  184. ):
  185. if callback is not None:
  186. r = callback(changes)
  187. if inspect.isawaitable(r):
  188. await r
  189. await anyio.to_thread.run_sync(process.stop)
  190. process = await anyio.to_thread.run_sync(start_process, target, target_type, args, kwargs, changes)
  191. reloads += 1
  192. await anyio.to_thread.run_sync(process.stop)
  193. return reloads
  194. # Use spawn context to make sure code run in subprocess
  195. # does not reuse imported modules in main process/context
  196. spawn_context = get_context('spawn')
  197. def split_cmd(cmd: str) -> list[str]:
  198. import platform
  199. posix = platform.uname().system.lower() != 'windows'
  200. return shlex.split(cmd, posix=posix)
  201. def start_process(
  202. target: str | Callable[..., Any],
  203. target_type: "Literal['function', 'command']",
  204. args: tuple[Any, ...],
  205. kwargs: dict[str, Any] | None,
  206. changes: set[FileChange] | None = None,
  207. ) -> 'CombinedProcess':
  208. if changes is None:
  209. changes_env_var = '[]'
  210. else:
  211. changes_env_var = json.dumps([[c.raw_str(), p] for c, p in changes])
  212. os.environ['WATCHFILES_CHANGES'] = changes_env_var
  213. process: SpawnProcess | subprocess.Popen[bytes]
  214. if target_type == 'function':
  215. kwargs = kwargs or {}
  216. if isinstance(target, str):
  217. args = target, get_tty_path(), args, kwargs
  218. target_ = run_function
  219. kwargs = {}
  220. else:
  221. target_ = target
  222. process = spawn_context.Process(target=target_, args=args, kwargs=kwargs)
  223. process.start()
  224. else:
  225. if args or kwargs:
  226. logger.warning('ignoring args and kwargs for "command" target')
  227. assert isinstance(target, str), 'target must be a string to run as a command'
  228. popen_args = split_cmd(target)
  229. process = subprocess.Popen(popen_args)
  230. return CombinedProcess(process)
  231. def detect_target_type(target: str | Callable[..., Any]) -> "Literal['function', 'command']":
  232. """
  233. Used by [`run_process`][watchfiles.run_process], [`arun_process`][watchfiles.arun_process]
  234. and indirectly the CLI to determine the target type with `target_type` is `auto`.
  235. Detects the target type - either `function` or `command`. This method is only called with `target_type='auto'`.
  236. The following logic is employed:
  237. * If `target` is not a string, it is assumed to be a function
  238. * If `target` ends with `.py` or `.sh`, it is assumed to be a command
  239. * Otherwise, the target is assumed to be a function if it matches the regex `[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)+`
  240. If this logic does not work for you, specify the target type explicitly using the `target_type` function argument
  241. or `--target-type` command line argument.
  242. Args:
  243. target: The target value
  244. Returns:
  245. either `'function'` or `'command'`
  246. """
  247. if not isinstance(target, str):
  248. return 'function'
  249. elif target.endswith(('.py', '.sh')):
  250. return 'command'
  251. elif re.fullmatch(r'[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+', target):
  252. return 'function'
  253. else:
  254. return 'command'
  255. class CombinedProcess:
  256. def __init__(self, p: 'SpawnProcess | subprocess.Popen[bytes]'):
  257. self._p = p
  258. assert self.pid is not None, 'process not yet spawned'
  259. def stop(self, sigint_timeout: int = 5, sigkill_timeout: int = 1) -> None:
  260. os.environ.pop('WATCHFILES_CHANGES', None)
  261. if self.is_alive():
  262. logger.debug('stopping process...')
  263. os.kill(self.pid, signal.SIGINT)
  264. try:
  265. self.join(sigint_timeout)
  266. except subprocess.TimeoutExpired:
  267. # Capture this exception to allow the self.exitcode to be reached.
  268. # This will allow the SIGKILL to be sent, otherwise it is swallowed up.
  269. logger.warning('SIGINT timed out after %r seconds', sigint_timeout)
  270. pass
  271. if self.exitcode is None:
  272. logger.warning('process has not terminated, sending SIGKILL')
  273. os.kill(self.pid, signal.SIGKILL)
  274. self.join(sigkill_timeout)
  275. else:
  276. logger.debug('process stopped')
  277. else:
  278. logger.warning('process already dead, exit code: %d', self.exitcode)
  279. def is_alive(self) -> bool:
  280. if isinstance(self._p, SpawnProcess):
  281. return self._p.is_alive()
  282. else:
  283. return self._p.poll() is None
  284. @property
  285. def pid(self) -> int:
  286. # we check the process has always been spawned when CombinedProcess is initialised
  287. return self._p.pid # type: ignore[return-value]
  288. def join(self, timeout: int) -> None:
  289. if isinstance(self._p, SpawnProcess):
  290. self._p.join(timeout)
  291. else:
  292. self._p.wait(timeout)
  293. @property
  294. def exitcode(self) -> int | None:
  295. if isinstance(self._p, SpawnProcess):
  296. return self._p.exitcode
  297. else:
  298. return self._p.returncode
  299. def run_function(function: str, tty_path: str | None, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
  300. with set_tty(tty_path):
  301. func = import_string(function)
  302. func(*args, **kwargs)
  303. def import_string(dotted_path: str) -> Any:
  304. """
  305. Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the
  306. last name in the path. Raise ImportError if the import fails.
  307. """
  308. try:
  309. module_path, class_name = dotted_path.strip(' ').rsplit('.', 1)
  310. except ValueError as e:
  311. raise ImportError(f'"{dotted_path}" doesn\'t look like a module path') from e
  312. module = import_module(module_path)
  313. try:
  314. return getattr(module, class_name)
  315. except AttributeError as e:
  316. raise ImportError(f'Module "{module_path}" does not define a "{class_name}" attribute') from e
  317. def get_tty_path() -> str | None: # pragma: no cover
  318. """
  319. Return the path to the current TTY, if any.
  320. Virtually impossible to test in pytest, hence no cover.
  321. """
  322. try:
  323. return os.ttyname(sys.stdin.fileno())
  324. except OSError:
  325. # fileno() always fails with pytest
  326. return '/dev/tty'
  327. except AttributeError:
  328. # on Windows. No idea of a better solution
  329. return None
  330. @contextlib.contextmanager
  331. def set_tty(tty_path: str | None) -> Generator[None, None, None]:
  332. if tty_path:
  333. try:
  334. with open(tty_path) as tty: # pragma: no cover
  335. sys.stdin = tty
  336. yield
  337. except OSError:
  338. # eg. "No such device or address: '/dev/tty'", see https://github.com/samuelcolvin/watchfiles/issues/40
  339. yield
  340. else:
  341. # currently on windows tty_path is None and there's nothing we can do here
  342. yield
  343. def raise_keyboard_interrupt(signum: int, _frame: Any) -> None: # pragma: no cover
  344. logger.warning('received signal %s, raising KeyboardInterrupt', signal.Signals(signum))
  345. raise KeyboardInterrupt
  346. def catch_sigterm() -> None:
  347. """
  348. Catch SIGTERM and raise KeyboardInterrupt instead. This means watchfiles will stop quickly
  349. on `docker compose stop` and other cases where SIGTERM is sent.
  350. Without this the watchfiles process will be killed while a running process will continue uninterrupted.
  351. """
  352. logger.debug('registering handler for SIGTERM on watchfiles process %d', os.getpid())
  353. signal.signal(signal.SIGTERM, raise_keyboard_interrupt)