@@ -69,6 +69,19 @@ attribute flag:
69
69
<script type =" py" src =" ./my-worker-code.py" worker ></script >
70
70
```
71
71
72
+ You may also want to add a ` name ` attribute to the tag, so you can use
73
+ ` pyscript.workers ` in the main thread to retrieve a reference to the worker:
74
+
75
+ ``` html
76
+ <script type =" py" src =" ./my-worker-code.py" worker name =" my-worker" ></script >
77
+ ```
78
+
79
+ ``` python
80
+ from pyscript import workers
81
+
82
+ my_worker = await workers[" my-worker" ]
83
+ ```
84
+
72
85
Alternatively, to launch a worker from within Python running on the main thread
73
86
use the [ pyscript.PyWorker] ( ../../api/#pyscriptpyworker ) class and you must
74
87
reference both the target Python script and interpreter type:
@@ -77,7 +90,7 @@ reference both the target Python script and interpreter type:
77
90
from pyscript import PyWorker
78
91
79
92
# The type MUST be given and can be either `micropython` or `pyodide`
80
- PyWorker(" my-worker-code.py" , type = " micropython" )
93
+ my_worker = PyWorker(" my-worker-code.py" , type = " micropython" )
81
94
```
82
95
83
96
## Worker interactions
@@ -121,6 +134,34 @@ greeting = sync.hello("PyScript")
121
134
window.console.log(greeting)
122
135
```
123
136
137
+ Alternatively, for the main thread to call functions in a worker, specify the
138
+ functions in a ` __export__ ` list:
139
+
140
+ ``` python title="Python code on the worker."
141
+ import sys
142
+
143
+ def version ():
144
+ return sys.version
145
+
146
+ # Define what to export to the main thread.
147
+ __export__ = [" version" , ]
148
+ ```
149
+
150
+ Then ensure you have a reference to the worker in the main thread (for
151
+ instance, by using the ` pyscript.workers ` ):
152
+
153
+ ``` html title="Creating a named worker in the web page."
154
+ <script type =" py" src =" ./my-worker-code.py" worker name =" my-worker" ></script >
155
+ ```
156
+
157
+ ``` python title="Referencing and using the worker from the main thread."
158
+ from pyscript import workers
159
+
160
+ my_worker = await workers[" my-worker" ]
161
+
162
+ print (await my_worker.version())
163
+ ```
164
+
124
165
The values passed between the main thread and the worker ** must be
125
166
serializable** . Try the example given above via
126
167
[ this project on PyScript.com] ( https://pyscript.com/@ntoll/tiny-silence/latest ) .
0 commit comments