0
# Interactive Mode
1
2
Fire provides interactive REPL functionality that allows users to drop into a Python shell with access to CLI components and execution context, making it valuable for debugging, exploration, and rapid prototyping.
3
4
## Capabilities
5
6
### Interactive REPL Embedding
7
8
Drop into a Python REPL with specified variables available in the local namespace.
9
10
```python { .api }
11
def Embed(variables, verbose=False):
12
"""
13
Drop into Python REPL with variables available as local variables.
14
15
Automatically detects and uses IPython if available, otherwise falls back
16
to the built-in Python REPL using the code module's InteractiveConsole.
17
18
Parameters:
19
- variables: Dictionary of variables to make available (keys=names, values=objects)
20
- verbose: Whether to include 'hidden' members (names starting with _)
21
"""
22
```
23
24
## Usage Examples
25
26
**Using the --interactive flag:**
27
```python
28
import fire
29
30
class DataProcessor:
31
def __init__(self):
32
self.data = []
33
34
def load(self, filename):
35
# Load data from file
36
self.data = [1, 2, 3, 4, 5] # Example data
37
return f"Loaded {len(self.data)} items"
38
39
def process(self):
40
return [x * 2 for x in self.data]
41
42
if __name__ == '__main__':
43
fire.Fire(DataProcessor)
44
# Command line: python script.py load data.txt -- --interactive
45
# After loading, drops into REPL with processor instance available
46
```
47
48
**Programmatic interactive embedding:**
49
```python
50
import fire
51
from fire import interact
52
53
def analyze_data(data_file, algorithm='default'):
54
# Process data
55
data = load_data(data_file) # Hypothetical function
56
results = run_algorithm(data, algorithm) # Hypothetical function
57
58
# Drop into interactive mode for exploration
59
interact.Embed({
60
'data': data,
61
'results': results,
62
'algorithm': algorithm
63
})
64
65
return results
66
67
if __name__ == '__main__':
68
fire.Fire(analyze_data)
69
```
70
71
**Custom interactive session:**
72
```python
73
import fire
74
from fire import interact
75
76
class DebugTool:
77
def __init__(self):
78
self.debug_info = {}
79
80
def debug_session(self, context_name="debug"):
81
"""Start interactive debugging session."""
82
import sys
83
import traceback
84
85
# Gather debugging context
86
frame = sys._getframe(1)
87
local_vars = frame.f_locals
88
global_vars = frame.f_globals
89
90
debug_context = {
91
'locals': local_vars,
92
'globals': global_vars,
93
'traceback': traceback,
94
'sys': sys
95
}
96
97
print(f"Starting debug session: {context_name}")
98
interact.Embed(debug_context, verbose=True)
99
100
if __name__ == '__main__':
101
fire.Fire(DebugTool)
102
```
103
104
## Interactive Features
105
106
**Automatic variable detection:**
107
When using Fire's `--interactive` flag, the REPL automatically includes:
108
- The current component being processed
109
- The execution trace showing the path taken
110
- Any intermediate results
111
- The final result of the command
112
113
**IPython integration:**
114
If IPython is installed, Fire automatically uses it for enhanced interactive features:
115
- Syntax highlighting
116
- Tab completion
117
- Magic commands
118
- Rich output formatting
119
- Command history
120
121
**Fallback to built-in REPL:**
122
When IPython is not available, Fire uses Python's built-in `code.InteractiveConsole` with:
123
- Basic command-line editing
124
- Exception handling
125
- Variable access
126
127
## Usage Patterns
128
129
**Debugging failed commands:**
130
```bash
131
python my_cli.py problematic_command arg1 arg2 -- --interactive
132
# Examine variables and state when command fails
133
```
134
135
**Exploring API interactively:**
136
```bash
137
python my_cli.py -- --interactive
138
# Start with base component and explore methods/properties
139
```
140
141
**Data science workflows:**
142
```python
143
import fire
144
from fire import interact
145
146
def load_and_explore(dataset_path):
147
import pandas as pd
148
149
df = pd.read_csv(dataset_path)
150
summary = df.describe()
151
152
# Drop into interactive mode for exploration
153
interact.Embed({
154
'df': df,
155
'summary': summary,
156
'pd': pd
157
})
158
159
return summary
160
161
if __name__ == '__main__':
162
fire.Fire(load_and_explore)
163
# python script.py data.csv
164
# Automatically drops into REPL with DataFrame available
165
```
166
167
The interactive mode bridges the gap between command-line usage and Python REPL development, making Fire an excellent tool for both scripting and interactive data exploration.