or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-watchfiles

Simple, modern and high performance file watching and code reload in python.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/watchfiles@1.1.x

To install, run

npx @tessl/cli install tessl/pypi-watchfiles@1.1.0

0

# watchfiles

1

2

Simple, modern and high performance file watching and code reload in Python. Built on top of the Rust notify library for efficient file system event handling, watchfiles provides both synchronous and asynchronous APIs for monitoring file changes with extensive filtering and configuration options.

3

4

## Package Information

5

6

- **Package Name**: watchfiles

7

- **Package Type**: PyPI package

8

- **Language**: Python (with Rust extensions)

9

- **Installation**: `pip install watchfiles`

10

- **Python Version**: 3.9 - 3.14

11

- **Dependencies**: anyio>=3.0.0

12

13

## Core Imports

14

15

```python

16

import watchfiles

17

```

18

19

Common imports for main functionality:

20

21

```python

22

from watchfiles import watch, awatch, run_process, arun_process, Change

23

```

24

25

Filter classes:

26

27

```python

28

from watchfiles import DefaultFilter, PythonFilter, BaseFilter

29

```

30

31

Process utilities:

32

33

```python

34

from watchfiles import detect_target_type, import_string

35

```

36

37

CLI functionality:

38

39

```python

40

from watchfiles.cli import cli

41

```

42

43

Version information:

44

45

```python

46

from watchfiles import VERSION

47

```

48

49

## Basic Usage

50

51

```python

52

from watchfiles import watch

53

54

# Watch a directory for changes

55

for changes in watch('./src'):

56

print(f'Files changed: {changes}')

57

```

58

59

Async usage:

60

61

```python

62

import asyncio

63

from watchfiles import awatch

64

65

async def monitor_files():

66

async for changes in awatch('./src'):

67

print(f'Files changed: {changes}')

68

69

asyncio.run(monitor_files())

70

```

71

72

Process restarting on file changes:

73

74

```python

75

from watchfiles import run_process

76

77

# Restart a Python function when files change

78

def main_app():

79

print("App is running...")

80

81

run_process('./src', target=main_app)

82

```

83

84

## Architecture

85

86

watchfiles consists of four main components:

87

88

- **Core Watching**: Sync/async file monitoring using Rust notify library for high performance

89

- **Process Management**: Automatic process restarting with signal handling and graceful shutdown

90

- **Filtering System**: Flexible file filtering with built-in filters for common use cases

91

- **CLI Interface**: Command-line tool for development workflows and process management

92

93

The Rust-based core (`_rust_notify`) handles low-level file system notifications efficiently across platforms, while the Python layer provides convenient APIs and integration with async frameworks.

94

95

## Capabilities

96

97

### File Watching

98

99

Core synchronous and asynchronous file watching functionality with configurable debouncing, filtering, and event handling. Supports watching multiple paths recursively with cross-platform compatibility.

100

101

```python { .api }

102

def watch(

103

*paths: Union[Path, str],

104

watch_filter: Optional[Callable[[Change, str], bool]] = DefaultFilter(),

105

debounce: int = 1_600,

106

step: int = 50,

107

stop_event: Optional[AbstractEvent] = None,

108

rust_timeout: int = 5_000,

109

yield_on_timeout: bool = False,

110

debug: Optional[bool] = None,

111

raise_interrupt: bool = True,

112

force_polling: Optional[bool] = None,

113

poll_delay_ms: int = 300,

114

recursive: bool = True,

115

ignore_permission_denied: Optional[bool] = None

116

) -> Generator[Set[FileChange], None, None]: ...

117

118

async def awatch(

119

*paths: Union[Path, str],

120

# Same parameters as watch

121

) -> AsyncGenerator[Set[FileChange], None]: ...

122

```

123

124

[File Watching](./file-watching.md)

125

126

### Process Management

127

128

Automatic process restarting and management when files change, supporting both Python functions and shell commands with configurable signal handling and graceful shutdown.

129

130

```python { .api }

131

def run_process(

132

*paths: Union[Path, str],

133

target: Union[str, Callable[..., Any]],

134

args: Tuple[Any, ...] = (),

135

kwargs: Optional[Dict[str, Any]] = None,

136

target_type: Literal['function', 'command', 'auto'] = 'auto',

137

callback: Optional[Callable[[Set[FileChange]], None]] = None,

138

watch_filter: Optional[Callable[[Change, str], bool]] = DefaultFilter(),

139

grace_period: float = 0,

140

# Additional watch parameters...

141

) -> int: ...

142

143

async def arun_process(

144

*paths: Union[Path, str],

145

# Same parameters as run_process

146

) -> int: ...

147

```

148

149

[Process Management](./process-management.md)

150

151

### File Filtering

152

153

Flexible filtering system to control which file changes are monitored, with built-in filters for common patterns and base classes for custom filtering logic.

154

155

```python { .api }

156

class BaseFilter:

157

ignore_dirs: Sequence[str] = ()

158

ignore_entity_patterns: Sequence[str] = ()

159

ignore_paths: Sequence[Union[str, Path]] = ()

160

161

def __init__(self) -> None: ...

162

def __call__(self, change: Change, path: str) -> bool: ...

163

164

class DefaultFilter(BaseFilter):

165

def __init__(

166

self,

167

*,

168

ignore_dirs: Optional[Sequence[str]] = None,

169

ignore_entity_patterns: Optional[Sequence[str]] = None,

170

ignore_paths: Optional[Sequence[Union[str, Path]]] = None,

171

) -> None: ...

172

173

class PythonFilter(DefaultFilter):

174

extensions: tuple

175

176

def __init__(

177

self,

178

*,

179

ignore_paths: Optional[Sequence[Union[str, Path]]] = None,

180

extra_extensions: Sequence[str] = (),

181

) -> None: ...

182

```

183

184

[File Filtering](./file-filtering.md)

185

186

### CLI Interface

187

188

Command-line interface for watching files and running commands or Python functions when changes are detected, providing development workflow integration without writing Python code.

189

190

```python { .api }

191

def cli(*args_: str) -> None:

192

"""

193

Watch one or more directories and execute either a shell command or a python function on file changes.

194

195

Parameters:

196

- *args_: Command line arguments, defaults to sys.argv[1:] if not provided

197

"""

198

199

def resolve_path(path_str: str) -> Path:

200

"""

201

Resolve a path string to an absolute Path object.

202

203

Parameters:

204

- path_str: String representation of the path

205

206

Returns:

207

Path: Resolved absolute path

208

"""

209

```

210

211

[CLI Interface](./cli.md)

212

213

## Types

214

215

```python { .api }

216

class Change(IntEnum):

217

"""Enum representing the type of change that occurred."""

218

added = 1

219

modified = 2

220

deleted = 3

221

222

def raw_str(self) -> str: ...

223

224

FileChange = Tuple[Change, str]

225

226

VERSION: str

227

```

228

229

## Environment Variables

230

231

watchfiles respects several environment variables for configuration:

232

233

- `WATCHFILES_FORCE_POLLING`: Enable/disable force polling mode

234

- `WATCHFILES_POLL_DELAY_MS`: Set polling delay in milliseconds

235

- `WATCHFILES_DEBUG`: Enable debug output

236

- `WATCHFILES_IGNORE_PERMISSION_DENIED`: Ignore permission denied errors

237

- `WATCHFILES_CHANGES`: JSON string of changes (automatically set for subprocess targets)

238

239

## CLI Usage

240

241

```bash

242

# Watch current directory and run a Python function

243

watchfiles my_module.main

244

245

# Watch specific directories with filtering

246

watchfiles --filter python 'pytest --lf' src tests

247

248

# Run shell command on changes

249

watchfiles 'echo "Files changed!"' ./src

250

```