@@ -69,6 +69,19 @@ attribute flag:
6969<script type =" py" src =" ./my-worker-code.py" worker ></script >
7070```
7171
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+
7285Alternatively, to launch a worker from within Python running on the main thread
7386use the [ pyscript.PyWorker] ( ../../api/#pyscriptpyworker ) class and you must
7487reference both the target Python script and interpreter type:
@@ -77,7 +90,7 @@ reference both the target Python script and interpreter type:
7790from pyscript import PyWorker
7891
7992# 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" )
8194```
8295
8396## Worker interactions
@@ -121,6 +134,34 @@ greeting = sync.hello("PyScript")
121134window.console.log(greeting)
122135```
123136
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+
124165The values passed between the main thread and the worker ** must be
125166serializable** . Try the example given above via
126167[ this project on PyScript.com] ( https://pyscript.com/@ntoll/tiny-silence/latest ) .
0 commit comments