scout-rig 0.2.5 → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.vimproject +31 -13
- data/README.md +27 -4
- data/Rakefile +1 -0
- data/VERSION +1 -1
- data/doc/Improvements.md +396 -0
- data/doc/StartHere.md +95 -0
- data/doc/developer/Architecture.md +232 -0
- data/doc/developer/DataConversionInternals.md +407 -0
- data/doc/developer/DesignPrinciples.md +254 -0
- data/doc/developer/PythonTaskRunnerInternals.md +371 -0
- data/doc/developer/PythonWorkflowInternals.md +539 -0
- data/doc/developer/ScoutPythonInternals.md +504 -0
- data/doc/user/Cookbook.md +337 -0
- data/doc/user/DefiningPythonTasks.md +708 -0
- data/doc/user/DrivingWorkflowsFromPython.md +418 -0
- data/doc/user/IteratingPythonData.md +142 -0
- data/doc/user/PassingDataToPython.md +223 -0
- data/doc/user/PythonEnvironments.md +197 -0
- data/doc/user/RunningPythonFromRuby.md +267 -0
- data/doc/user/ScriptingPython.md +281 -0
- data/doc/user/TestingAndPackaging.md +487 -0
- data/lib/scout/python/script.rb +11 -2
- data/lib/scout/python/util.rb +9 -0
- data/lib/scout/workflow/python/inputs.rb +33 -23
- data/lib/scout/workflow/python/task.rb +219 -18
- data/lib/scout/workflow/python.rb +236 -9
- data/lib/scout-rig/testing/availability.rb +608 -0
- data/python/README.md +51 -0
- data/python/scout/__init__.py +2 -0
- data/python/scout/runner.py +193 -29
- data/python/scout/task_errors.py +6 -0
- data/research/00_scope_and_themes.md +131 -0
- data/research/data-conversion-and-scripting-analysis.md +209 -0
- data/research/design-philosophy-analysis.md +246 -0
- data/research/python-helper-package-analysis.md +272 -0
- data/research/pythonworkflow-analysis.md +199 -0
- data/research/scoutpython-bridge-analysis.md +185 -0
- data/research/synthesis-report.md +109 -0
- data/research/testing-availability-baseline.md +1625 -0
- data/research/testing-availability-final-report.md +500 -0
- data/research/validation-report.md +149 -0
- data/scout-rig.gemspec +35 -5
- data/test/scout/python/test_util.rb +13 -0
- data/test/scout/test_python.rb +10 -0
- data/test/scout/workflow/python/test_task.rb +1119 -1
- data/test/scout-rig/testing/test_availability.rb +495 -0
- data/test/scout-rig/testing/test_test_support.rb +166 -0
- data/test/test_helper.rb +96 -19
- metadata +47 -4
- data/doc/Python.md +0 -482
- data/doc/PythonWorkflow.md +0 -163
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
# Scripting Python
|
|
2
|
+
|
|
3
|
+
This document explains how to run ad-hoc Python scripts from Ruby using
|
|
4
|
+
the `script()` facility, inject Ruby variables, and retrieve results.
|
|
5
|
+
|
|
6
|
+
## Audience
|
|
7
|
+
|
|
8
|
+
This page is intended for:
|
|
9
|
+
|
|
10
|
+
- ✓ Workflow authors who need to run Python code as a script
|
|
11
|
+
- ✓ Agent developers running one-off Python computations
|
|
12
|
+
- ✗ Framework contributors (see [Data Conversion Internals](../developer/DataConversionInternals.md))
|
|
13
|
+
|
|
14
|
+
## When to use this
|
|
15
|
+
|
|
16
|
+
Use `script()` when you need to:
|
|
17
|
+
|
|
18
|
+
- Run a Python code block that uses multiple libraries (pandas, numpy, sklearn).
|
|
19
|
+
- Pass Ruby variables (including TSV) into Python.
|
|
20
|
+
- Get a result value back in Ruby.
|
|
21
|
+
- Avoid the complexity of managing PyCall sessions and imports.
|
|
22
|
+
|
|
23
|
+
For short one-liners or when you need to interact with Python objects
|
|
24
|
+
in-memory, use [Running Python from Ruby](RunningPythonFromRuby.md) instead.
|
|
25
|
+
|
|
26
|
+
## Core concepts
|
|
27
|
+
|
|
28
|
+
`ScoutPython.script(text, variables = {})` runs a Python script in a
|
|
29
|
+
**subprocess** and returns the value of the Python variable `result`.
|
|
30
|
+
|
|
31
|
+
This is fundamentally different from `run`:
|
|
32
|
+
- `run` executes in the current Ruby process via PyCall.
|
|
33
|
+
- `script` spawns a new Python process, runs the script, and reads back
|
|
34
|
+
the result from a file.
|
|
35
|
+
|
|
36
|
+
The advantage of `script()` is isolation: each call gets a clean Python
|
|
37
|
+
environment with no state leakage. The tradeoff is overhead (process
|
|
38
|
+
startup + file I/O).
|
|
39
|
+
|
|
40
|
+
## Typical usage
|
|
41
|
+
|
|
42
|
+
### Basic script
|
|
43
|
+
|
|
44
|
+
```ruby
|
|
45
|
+
result = ScoutPython.script <<~PY, value: 2
|
|
46
|
+
result = value * 3
|
|
47
|
+
PY
|
|
48
|
+
puts result # => 6
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
What happens:
|
|
52
|
+
1. The variable `value: 2` is serialized as `value = 2` (Python literal).
|
|
53
|
+
2. The script body sets `result`.
|
|
54
|
+
3. A "save result" snippet is appended: `result` is pickled to a temp file.
|
|
55
|
+
4. Ruby reads the pickle and returns `6`.
|
|
56
|
+
|
|
57
|
+
Note that the script text is fed to `python` on **stdin** — `script()` never
|
|
58
|
+
writes a `.py` file. The temp files involved are the pickle result file and
|
|
59
|
+
one TSV dump per TSV variable (see "Failure semantics and temp files" below).
|
|
60
|
+
|
|
61
|
+
### Passing a TSV
|
|
62
|
+
|
|
63
|
+
When you pass a TSV as a variable, it is written to a temporary file and
|
|
64
|
+
loaded into Python as a pandas DataFrame via the Python `scout.tsv()`
|
|
65
|
+
function:
|
|
66
|
+
|
|
67
|
+
```ruby
|
|
68
|
+
tsv = TSV.setup({}, "Key~ValueA,ValueB#:type=:list")
|
|
69
|
+
tsv["k1"] = ["a1", "b1"]
|
|
70
|
+
tsv["k2"] = ["a2", "b2"]
|
|
71
|
+
|
|
72
|
+
result = ScoutPython.script <<~PY, df: tsv
|
|
73
|
+
result = df.loc["k2", "ValueB"]
|
|
74
|
+
PY
|
|
75
|
+
puts result # => "b2"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Passing multiple variables
|
|
79
|
+
|
|
80
|
+
```ruby
|
|
81
|
+
result = ScoutPython.script <<~PY, numbers: [1, 2, 3], factor: 10
|
|
82
|
+
result = [n * factor for n in numbers]
|
|
83
|
+
PY
|
|
84
|
+
puts result.inspect # => [10, 20, 30]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Variable types are serialized as follows:
|
|
88
|
+
|
|
89
|
+
| Ruby type | Python representation |
|
|
90
|
+
|-----------|----------------------|
|
|
91
|
+
| `nil` | `None` |
|
|
92
|
+
| `true` | `True` |
|
|
93
|
+
| `false` | `False` |
|
|
94
|
+
| Integer/Float | Literal number |
|
|
95
|
+
| String | Single-quoted literal |
|
|
96
|
+
| Symbol | Bare identifier |
|
|
97
|
+
| Array | Python list literal |
|
|
98
|
+
| Hash | Python dict literal |
|
|
99
|
+
| TSV | pandas DataFrame (via temp file + `scout.tsv()`) |
|
|
100
|
+
|
|
101
|
+
Details worth knowing, verified against the implementation:
|
|
102
|
+
|
|
103
|
+
- **Strings become single-quoted Python literals without escaping.** The
|
|
104
|
+
string `"it's"` is emitted as `'it's'`, which is a Python `SyntaxError`.
|
|
105
|
+
Strings containing a newline break the generated program for the same
|
|
106
|
+
reason. Double quotes (`'a"b'`), backslashes (Ruby `"a\\b"` → Python
|
|
107
|
+
`a\b`), tabs and non-ASCII text round-trip fine. If you must pass arbitrary
|
|
108
|
+
text, pass a filename or a TSV instead of a string variable.
|
|
109
|
+
- **`Symbol` values are emitted as bare Python names**, not strings: `:abc`
|
|
110
|
+
becomes `abc`. This only works for symbols that are also valid Python
|
|
111
|
+
identifiers; a symbol like `:d-f` is emitted verbatim and the generated
|
|
112
|
+
program then fails with a Python `SyntaxError`/`NameError`.
|
|
113
|
+
- **A `String` that starts with `":"` is stripped of the leading colon**: the
|
|
114
|
+
string `":abc"` becomes the bare Python name `abc`, and the exact string
|
|
115
|
+
`":NA"` becomes `None`. This is one way to pass `nil`, but it also means a
|
|
116
|
+
literal string beginning with `:` never reaches Python as itself.
|
|
117
|
+
- **`Float::INFINITY` becomes the Python name `inf`**, which is undefined
|
|
118
|
+
unless your script defines it (`from math import inf`).
|
|
119
|
+
- **Hash keys are coerced to strings**, including inside nested structures:
|
|
120
|
+
`{1 => 'a'}` becomes `{'1':'a'}` and `{[1,2] => 'a'}` becomes
|
|
121
|
+
`{'[1, 2]':'a'}`.
|
|
122
|
+
- **Only these types are accepted.** Anything else raises
|
|
123
|
+
`Type of object not known: ...`; a `Path` is serialized as its string
|
|
124
|
+
value.
|
|
125
|
+
|
|
126
|
+
### Getting results back with pandas
|
|
127
|
+
|
|
128
|
+
You can also use the `scout` Python package inside scripts to save
|
|
129
|
+
DataFrames back to TSV:
|
|
130
|
+
|
|
131
|
+
```ruby
|
|
132
|
+
tsv = TSV.setup({}, "Key~ValueA,ValueB#:type=:list")
|
|
133
|
+
tsv["k1"] = ["a1", "b1"]
|
|
134
|
+
|
|
135
|
+
TmpFile.with_file do |target|
|
|
136
|
+
ScoutPython.script <<~PY, df: tsv, target: target
|
|
137
|
+
import scout
|
|
138
|
+
df['ValueA'] = df['ValueA'].str.upper()
|
|
139
|
+
scout.save_tsv(target, df)
|
|
140
|
+
result = "done"
|
|
141
|
+
PY
|
|
142
|
+
TSV.open(target, type: :list)["k1"]["ValueA"] # => "A1"
|
|
143
|
+
end
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Result persistence
|
|
147
|
+
|
|
148
|
+
By default, results are pickled and loaded via the `python/pickle` Ruby gem.
|
|
149
|
+
If you prefer JSON (or if the pickle gem is unavailable), re-point the
|
|
150
|
+
aliases:
|
|
151
|
+
|
|
152
|
+
```ruby
|
|
153
|
+
class << ScoutPython
|
|
154
|
+
alias save_script_result save_script_result_json
|
|
155
|
+
alias load_result load_json
|
|
156
|
+
end
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Now results will be serialized as JSON instead of pickle.
|
|
160
|
+
|
|
161
|
+
### What actually round-trips
|
|
162
|
+
|
|
163
|
+
The two back-ends are **not** equivalent, and neither is universal. Both
|
|
164
|
+
columns were verified with probes against the current stack (Ruby 3.3,
|
|
165
|
+
Python 3.13, `python-pickle` 0.2.0):
|
|
166
|
+
|
|
167
|
+
| Result value | pickle (default) | JSON backend |
|
|
168
|
+
|--------------|------------------|--------------|
|
|
169
|
+
| `True` / `False` | `true` / `false` | `true` / `false` |
|
|
170
|
+
| float `1.5` | `1.5` | `1.5` |
|
|
171
|
+
| string `"a"` | `"a"` | `"a"` |
|
|
172
|
+
| list / dict | list / hash | array / hash |
|
|
173
|
+
| `bytes b"x"` | `"x"` | not JSON-serializable |
|
|
174
|
+
| float `inf`, `nan` | `Float::INFINITY`, `Float::NAN` | Ruby raises `JSON::ParserError` |
|
|
175
|
+
| integer `1`..`255` | `1`..`255` | OK |
|
|
176
|
+
| integer `256`, `300`, `-1` | **`Python::Pickle::InvalidFormat`** | OK |
|
|
177
|
+
| datetime / numpy array / DataFrame | opaque `Python::Pickle::PyObject` or `InvalidFormat` | `TypeError` on the Python side unless converted first |
|
|
178
|
+
|
|
179
|
+
Two consequences follow:
|
|
180
|
+
|
|
181
|
+
- **The default pickle backend cannot read most integers.** Protocol 4 emits
|
|
182
|
+
`BININT2`/`BININT` opcodes for anything outside `0..255`, and
|
|
183
|
+
`python/pickle` 0.2.0 does not implement those opcodes, so `result = 300`
|
|
184
|
+
raises `Python::Pickle::InvalidFormat: invalid opcode (74) for protocol 4`
|
|
185
|
+
even though the pickle was written by the same Python that scout-rig
|
|
186
|
+
launches. Small positive integers (0-255), floats, strings, booleans,
|
|
187
|
+
`None`, lists and dicts decode fine. Prefer returning floats or strings,
|
|
188
|
+
or switch to the JSON backend, when the result is numeric.
|
|
189
|
+
- **`result = None` is indistinguishable from "script failed to set
|
|
190
|
+
`result`"** — both return Ruby `nil`. The save snippet writes nothing when
|
|
191
|
+
`result` is `None` or undefined, and `script()` returns `nil` whenever the
|
|
192
|
+
result file is absent.
|
|
193
|
+
|
|
194
|
+
## Common mistakes
|
|
195
|
+
|
|
196
|
+
### Forgetting to set the `result` variable
|
|
197
|
+
|
|
198
|
+
The script must set a Python variable named `result`. If it doesn't (or sets
|
|
199
|
+
it to `None`), no result file is written and `script()` silently returns
|
|
200
|
+
`nil`; it does **not** raise. The save snippet is wrapped in
|
|
201
|
+
`try: result / except NameError: result = None`, so a missing variable is
|
|
202
|
+
absorbed rather than reported:
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
# Bad — no result variable
|
|
206
|
+
ScoutPython.script <<~PY
|
|
207
|
+
x = 42
|
|
208
|
+
PY
|
|
209
|
+
# => nil, no error
|
|
210
|
+
|
|
211
|
+
# Good
|
|
212
|
+
ScoutPython.script <<~PY
|
|
213
|
+
result = 42
|
|
214
|
+
PY
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Exceptions and error reporting
|
|
218
|
+
|
|
219
|
+
Any unhandled Python exception, syntax error or non-zero exit makes
|
|
220
|
+
`script()` raise `ConcurrentStreamProcessFailed`. The message contains only
|
|
221
|
+
the **last line of the Python traceback** (scout-essentials keeps a rolling
|
|
222
|
+
one-line log of the subprocess):
|
|
223
|
+
|
|
224
|
+
```
|
|
225
|
+
Process 12 failed - Error joining fd 8. Last log line: ValueError: BOOM
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
So the exception class and message survive, but the traceback body (file and
|
|
229
|
+
line numbers) is lost. To see it, set `Log.severity = 0` (or run with
|
|
230
|
+
`SCOUT_LOG=debug`), which makes `CMD.cmd_log` mirror the full stderr to the
|
|
231
|
+
Scout log/terminal. Note that the exception has no structured payload — it
|
|
232
|
+
only exposes `pid` and `msg`.
|
|
233
|
+
|
|
234
|
+
### Temp files and cleanup
|
|
235
|
+
|
|
236
|
+
- The generated program is passed on **stdin** to `env PYTHONPATH=... python`;
|
|
237
|
+
there is no `.py` temp file.
|
|
238
|
+
- TSV variables are each dumped to one temp file under Scout's `tmp/`
|
|
239
|
+
directory (name `tmp-<random>` from `TmpFile.tmp_file`, content = the TSV
|
|
240
|
+
text). The generated assignment is `name = scout.tsv('<path>')`, which is
|
|
241
|
+
a **single-quoted** Python literal interpolated directly into the program —
|
|
242
|
+
a TSV variable name containing an apostrophe would break it.
|
|
243
|
+
They are deleted right after the subprocess finishes, **including when the
|
|
244
|
+
script raises** — the cleanup line sits outside any error handling.
|
|
245
|
+
- The result file is a temp file that is **never** deleted by `script()`;
|
|
246
|
+
it stays behind on both success and failure (on failure it simply never
|
|
247
|
+
gets written).
|
|
248
|
+
|
|
249
|
+
### Using pickle for non-picklable objects
|
|
250
|
+
|
|
251
|
+
The default pickle persistence works for most Python objects, but some
|
|
252
|
+
objects (e.g., file handles, lambda functions) cannot be pickled. Use JSON
|
|
253
|
+
persistence if your result is a simple data structure (dict, list, str,
|
|
254
|
+
number).
|
|
255
|
+
|
|
256
|
+
### Performance for repeated calls
|
|
257
|
+
|
|
258
|
+
Each `script()` call spawns a new Python process. For repeated calls, use
|
|
259
|
+
`run` or `run_direct` to execute multiple operations in a single Python
|
|
260
|
+
session.
|
|
261
|
+
|
|
262
|
+
### Environment of the subprocess
|
|
263
|
+
|
|
264
|
+
The subprocess is launched as `env PYTHONPATH=<ScoutPython.paths joined by
|
|
265
|
+
':'> python`, which means:
|
|
266
|
+
|
|
267
|
+
- `ScoutPython.paths` is what makes `import scout` work; it is populated
|
|
268
|
+
from `Scout.python.find_all` (in this checkout, the repository's
|
|
269
|
+
`python/` directory).
|
|
270
|
+
- **Any `PYTHONPATH` you set in the parent process is discarded**, because
|
|
271
|
+
the `env` prefix replaces it rather than extending it. If your script
|
|
272
|
+
needs another Python path, add it with `ScoutPython.add_path(...)` before
|
|
273
|
+
calling `script()` (that list is also used for the in-process `sys.path`).
|
|
274
|
+
- The rest of the environment is inherited normally.
|
|
275
|
+
|
|
276
|
+
## See also
|
|
277
|
+
|
|
278
|
+
- [Passing Data to Python](PassingDataToPython.md) — In-process data conversion.
|
|
279
|
+
- [Running Python from Ruby](RunningPythonFromRuby.md) — In-process execution.
|
|
280
|
+
- [Data Conversion Internals](../developer/DataConversionInternals.md) — How
|
|
281
|
+
serialization works internally.
|