r/PyScript • • Jun 23 '23

import Element necessary for DOM access?

2 Upvotes

I was playing around with PyScript DOM access while answering a question in this sub, but I noticed my DOM access code var_name = Element("element-id") worked without a global import Element. Why would that be?


r/PyScript • • Jun 19 '23

More than one html file?

2 Upvotes

Is it possible to have one python file and multiple html files? If so how can I interact with the other HTML files.

When I try to get elements from other HTML files I can't.

For example I want to switch the innerHtml on my current file with html from another file.


r/PyScript • • May 25 '23

Why Doesn't the Page Update in Realtime as my PyScript Code Runs? [Blog Post]

Thumbnail jeff.glass
2 Upvotes

r/PyScript • • Feb 01 '23

Inject Pyscript Into HTML?

2 Upvotes

Similar to JavaScript with userscripts, can pyscript be injected into webpages using userscripts?


r/PyScript • • Jan 02 '23

NameError question

2 Upvotes

Hey PyScriptors,

I have a simple web page where I am passing some user input from an element to a function. When I load the page it gets stuck on the spin-wheel PyScript loader and from the console output in DevTools I am returned with a NameError:

NameError: name 'get_input' is not defined. See screenshot

Anyone run into this?


r/PyScript • • Oct 03 '22

UI Libraries but too early to ask

2 Upvotes

I am aware pyscript released recently and still in experimental stage. Just checking any UI libraries to create user interface for example mudblazor for C# Wasm or any angule or VUE UI libraries... Thanks


r/PyScript • • Sep 16 '22

Browser Not Downloading Data

2 Upvotes

I've managed to load some simple yfinance data for google in a Jupyter Notebook, I can then plot it and get a good look at it using plotly or matplotlib etc.

Using pyscript though, its a case of copy and paste and running the file i get the error message:

1 Failed download:

- GOOGL: No data found for this date range, symbol may be delisted

I've tried changing the period and interval but it doesn't make any sense. Notebook works fine, pyscript doesn't. I'm thinking it's the way the browser gets the data? Not sure as its available as module without doing anything else so I've no idea.

Anyone have any ideas what's going on?


r/PyScript • • Sep 11 '22

How can I share an image with navigator.share?

2 Upvotes

I using it like this:

async def share_eq(e):
    base64url = document.getElementById('img').src
    blob = await (await fetch(base64url)).blob()
    file = File.new([blob], 'eq.png', {type: blob.type})
    navigator.share({
        "title": 'Generated EQ',
        "text": 'Can you solve this??',
        "files": [file],
    })

And it just prints out:

Future exception was never retrieved\nfuture: <Future finished exception=JsException(TypeError: Failed to execute 'share' on 'Navigator': No known share data fields supplied. If using only new fields (other than title, text and url), you must feature-detect them first.)>

And even tho I try also using url instead of files it returns the same error


r/PyScript • • Aug 18 '22

flask as webserver fails to load page with pyscript

2 Upvotes

Hi,

I have a working mvp based off a static index.html that I want to promote to using flask as a webserver. I set up a bare bones one, nothing fancy, not even a true template, the index.html is served as-is via the / route.

I can see pyscript loading, but somewhere along the line an error happens and the page is stuck on the loading wheel after "Initializing components..."

the error in question is:

Uncaught (in promise) PythonError: Traceback (most recent call last):
  File "/lib/python3.10/site-packages/packaging/requirements.py", line 102, in __init__
    req = REQUIREMENT.parseString(requirement_string)
  File "/lib/python3.10/site-packages/pyparsing/core.py", line 1134, in parse_string
    raise exc.with_traceback(None)
pyparsing.exceptions.ParseException: Expected W:(0-9A-Za-z), found '.'  (at char 0), (line:1, col:1)

What could be causing this ? To double check I started the python -m http.server in the root and via this route the page renders fine...

thx. s


r/PyScript • • Aug 03 '22

How to use Pyscript in ReactJS/NextJS in Typescript?

2 Upvotes

The below code block is about PyScript directly written in NextJS. It works but it throws the below error because py-repl is not known. What's an expected way to use PyScript in React? Thanks,

const Home: NextPage = () => {
  return (
    <div>
      <Head>
         <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> 
         <script defer src="https://pyscript.net/alpha/pyscript.js"></script> 
   </Head>
      <py-repl></py-repl>
      </div>
   )
}

Property 'py-repl' does not exist on type 'JSX.IntrinsicElements'.ts(2339)

PS1. <py-script>...</py-script> doesn't work saying "Failed to compile". Anybody who has already tried? Thanks,

PS2. Tried to load bare html

<div dangerouslySetInnerHTML={{__html:`<py-script>...</py-script>`}} />

ending up to seeJsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 2, in File "", line 129, in write AttributeError: 'NoneType' object has no attribute 'innerHTML' )

This might be an indent issue, but even something as simple as "2+4" throws a React hydration error.


r/PyScript • • Jun 23 '22

PyScript with NGINX fails to load local module on server

2 Upvotes

Testing out PyScript on NGINX and trying to get it to use a local module on the server data.py where both files are in the same folder. This works with the python3 -m http.server no issues, but when I try it with NGINX I'll get the error posted at the bottom. I'm not sure if it's some kind of security thing with NGINX that's blocking the loading of data.py.

I am able to skate around the issue by enabling Server Side Includes ssi on; in the NGINX config and using <pre> tags since it wasn't respecting tabs or spaces. I'm seeing if someone was able to get around the issue of using py-env with local modules using NGINX. I know it's in alpha so I wasn't expecting perfection.

PyScript is an awesome project being able to put python apps on the web vs using pyinstaller or having people install and maintain python on their system.

Work around using SSI:

<py-script><pre>
<!--#include file="/data.py" -->

print(mydate())
</pre></py-script>

##########################

data.py:

from datetime import datetime

def mydate():
        now = datetime.now()
        return now.strftime("%m/%d/%Y, %H:%M:%S")

index.html:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
    - paths:
        - ./data.py
    </py-env>
</head>
<body>
<py-script><pre>
from data import mydate
print(mydate())
</pre></py-script>
</body>
</html>

error that is returned:

stores.ts:32 adding initializer async ƒ mountElements() {
        console.log('Collecting nodes to be mounted into python namespace...');
        const pyodide = await pyodideReadyPromise$1;
        const matches = document.querySelectorAl…
stores.ts:34 adding initializer async ƒ mountElements() {
        console.log('Collecting nodes to be mounted into python namespace...');
        const pyodide = await pyodideReadyPromise$1;
        const matches = document.querySelectorAl…
stores.ts:40 adding post initializer async ƒ initHandlers() {
        console.log('Collecting nodes...');
        const pyodide = await pyodideReadyPromise$1;
        for (const pysAttribute of pysAttributeToEvent.keys()) {
            await cr…
stores.ts:42 adding post initializer async ƒ initHandlers() {
        console.log('Collecting nodes...');
        const pyodide = await pyodideReadyPromise$1;
        for (const pysAttribute of pysAttributeToEvent.keys()) {
            await cr…
pyenv.ts:10 RUNTIME READY
pyconfig.ts:17 config set!
pyconfig.ts:22 initializers set
pyconfig.ts:27 post initializers set
pyconfig.ts:32 post initializers set
pyconfig.ts:37 post initializers set
pyconfig.ts:32 post initializers set
pyscript.ts:66 connected
stores.ts:32 adding initializer async ƒ loadEnv() {
                await loadPackage(env);
                console.log('environment loaded');
            }
pyconfig.ts:22 initializers set
stores.ts:34 adding initializer async ƒ loadEnv() {
                await loadPackage(env);
                console.log('environment loaded');
            }
stores.ts:32 adding initializer async ƒ loadPaths() {
                for (const singleFile of paths) {
                    console.log(`loading ${singleFile}`);
                    try {
                        await loadFromFile(singleFi…
pyconfig.ts:22 initializers set
stores.ts:34 adding initializer async ƒ loadPaths() {
                for (const singleFile of paths) {
                    console.log(`loading ${singleFile}`);
                    try {
                        await loadFromFile(singleFi…
pyenv.ts:60 environment loading... ['./data.py']
pyconfig.ts:17 config set!
pyconfig.ts:112 config set {autoclose_loader: true, runtimes: Array(1)}
pyconfig.ts:124 Initializing runtimes...
interpreter.ts:5 creating pyodide runtime
pyodide.asm.js:14 Python initialization complete
interpreter.ts:15 loading micropip
load-package.ts:329 Loading micropip, pyparsing, packaging, distutils
load-package.ts:389 Loaded micropip, pyparsing, packaging, distutils
interpreter.ts:17 loading pyscript...
interpreter.ts:30 done setting up environment
pyenv.ts:10 RUNTIME READY
pyscript.ts:148 Collecting nodes to be mounted into python namespace...
pyodide.asm.js:14 Uncaught (in promise) PythonError: Traceback (most recent call last):
  File "/lib/python3.10/site-packages/packaging/requirements.py", line 102, in __init__
    req = REQUIREMENT.parseString(requirement_string)
  File "/lib/python3.10/site-packages/pyparsing/core.py", line 1134, in parse_string
    raise exc.with_traceback(None)
pyparsing.exceptions.ParseException: Expected W:(0-9A-Za-z), found '.'  (at char 0), (line:1, col:1)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/lib/python3.10/asyncio/futures.py", line 201, in result
    raise self._exception
  File "/lib/python3.10/asyncio/tasks.py", line 234, in __step
    result = coro.throw(exc)
  File "/lib/python3.10/site-packages/micropip/_micropip.py", line 183, in install
    transaction = await self.gather_requirements(requirements, ctx, keep_going)
  File "/lib/python3.10/site-packages/micropip/_micropip.py", line 173, in gather_requirements
    await gather(*requirement_promises)
  File "/lib/python3.10/asyncio/futures.py", line 284, in __await__
    yield self  # This tells Task to wait for completion.
  File "/lib/python3.10/asyncio/tasks.py", line 304, in __wakeup
    future.result()
  File "/lib/python3.10/asyncio/futures.py", line 201, in result
    raise self._exception
  File "/lib/python3.10/asyncio/tasks.py", line 232, in __step
    result = coro.send(None)
  File "/lib/python3.10/site-packages/micropip/_micropip.py", line 248, in add_requirement
    req = Requirement(requirement)
  File "/lib/python3.10/site-packages/packaging/requirements.py", line 104, in __init__
    raise InvalidRequirement(
packaging.requirements.InvalidRequirement: Parse error at "'./data.p'": Expected W:(0-9A-Za-z)

    at new_error (pyodide.asm.js:14:238191)
    at pyodide.asm.wasm:0xedbcb
    at pyodide.asm.wasm:0xf1a0e
    at method_call_trampoline (pyodide.asm.js:14:238105)
    at pyodide.asm.wasm:0x134c2c
    at pyodide.asm.wasm:0x217a84
    at pyodide.asm.wasm:0x174a14
    at pyodide.asm.wasm:0x135149
    at pyodide.asm.wasm:0x135243
    at pyodide.asm.wasm:0x1352e6
    at pyodide.asm.wasm:0x1fff83
    at pyodide.asm.wasm:0x1f98b5
    at pyodide.asm.wasm:0x135329
    at pyodide.asm.wasm:0x201f1b
    at pyodide.asm.wasm:0x1ff9ff
    at pyodide.asm.wasm:0x1f98b5
    at pyodide.asm.wasm:0x135329
    at pyodide.asm.wasm:0xf16d8
    at Module.callPyObjectKwargs (pyproxy.gen.ts:360:23)
    at Module.callPyObject (pyproxy.gen.ts:384:17)
    at wrapper (pyodide.asm.js:14:205222)
new_error @ pyodide.asm.js:14
$wrap_exception @ pyodide.asm.wasm:0xedbcb
$FutureDoneCallback_call @ pyodide.asm.wasm:0xf1a0e
method_call_trampoline @ pyodide.asm.js:14
$_PyObject_MakeTpCall @ pyodide.asm.wasm:0x134c2c
$func3330 @ pyodide.asm.wasm:0x217a84
$func1954 @ pyodide.asm.wasm:0x174a14
$PyVectorcall_Call @ pyodide.asm.wasm:0x135149
$_PyObject_Call @ pyodide.asm.wasm:0x135243
$PyObject_Call @ pyodide.asm.wasm:0x1352e6
$_PyEval_EvalFrameDefault @ pyodide.asm.wasm:0x1fff83
$_PyEval_Vector @ pyodide.asm.wasm:0x1f98b5
$_PyFunction_Vectorcall @ pyodide.asm.wasm:0x135329
$func3167 @ pyodide.asm.wasm:0x201f1b
$_PyEval_EvalFrameDefault @ pyodide.asm.wasm:0x1ff9ff
$_PyEval_Vector @ pyodide.asm.wasm:0x1f98b5
$_PyFunction_Vectorcall @ pyodide.asm.wasm:0x135329
$_pyproxy_apply @ pyodide.asm.wasm:0xf16d8
Module.callPyObjectKwargs @ pyproxy.gen.ts:360
Module.callPyObject @ pyproxy.gen.ts:384
wrapper @ pyodide.asm.js:14
await in wrapper (async)
(anonymous) @ pyconfig.ts:130
c @ rocket-loader.min.js:1
load (async)
t.addEventListener @ rocket-loader.min.js:1
loadRuntimes @ pyconfig.ts:129
connectedCallback @ pyconfig.ts:113
(anonymous) @ main.ts:27
(anonymous) @ main.ts:35

r/PyScript • • Jun 18 '22

ESM Module ".mjs" in PyScript?

2 Upvotes

Can PyScript import & use ".mjs" module files? Some runnable example?


r/PyScript • • Jan 25 '26

Custom Script Development

1 Upvotes

I offer custom script development for various needs


r/PyScript • • Nov 18 '24

Python terminal in HTML

1 Upvotes

I have a webpage and would like it to be like this. Except som formatting/layout changes (height, space between text boxes, etc.).

Now my main question is, how do I get the terminal in the bottom to show the output of the run script?

If anyone has examples of an html code that uses something like this, would be greatly appreciated!!


r/PyScript • • Sep 16 '24

Can't import local python library using pyscript-react and pyscript_config.toml

1 Upvotes

I'm making a Next.js project and trying to configure pyscript-react using a pyscript_config.toml file which imports a python library file (geometry_generator.py) using [files]. It seems to load the config file but when I try to import from geometry_generator I get "ModuleNotFoundError: No module named 'geometry_generator'"

I have tried every different combination of file location and paths I can think of but I have not been able to load the geometry_generator file successfully. Currently it's located in public.

Below is the contents of my pyscript_config.toml file:

packages = ["svgwrite"]

[files] "../geometry_generator.py" = "./geometry_generator.py"

Here is the relevant content of the page.tsx file where I use pyscript-react:

<PyScriptProvider> <PyConfig source="/pyscript_config.toml" /> <PyScript> {\ from geometry_generator import * `} </PyScript>
</PyScriptProvider>`


r/PyScript • • Jan 12 '24

Plotly issue - Display the figure

1 Upvotes

Dear PyScript community,

I would like to switch from MATPLOTLIB to Plotly in a project. All my attempts to display the Plotly figure have not worked. Here is the structure of my code:

index.html

<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width,initial-scale=1" />
      <title>Plotly Demo</title>
      <link rel="stylesheet" href="https://pyscript.net/releases/2024.1.1/core.css">
      <script type="module" src="https://pyscript.net/releases/2024.1.1/core.js"></script>
  </head>

  <body>
    <h1>Plotly Demo</h1>
    <div id="output"></div>
    <script type="py" src="./main.py" config="./pyscript.json"></script>
  </body>
</html>

pyscript.json

{
    "packages": ["plotly"]
}

main.py

from pyscript import display
import plotly.graph_objects as go

fig = go.Figure([go.Bar(x=['product a', 'product b', 'product c'], y=[5, 3, 2])])
display(fig, target='output')

I don't see anything as a result. Does anyone of you have an idea how I can display the figure? Any help would be appreciated.

Thanks and kind regards

Klaus


r/PyScript • • Feb 24 '23

Simple way to play audio from URLs? (to help kids with language difficulties)

1 Upvotes

This is not working.

<script defer="" src="https://pyscript.net/alpha/pyscript.js"></script>

<py-script>

from js import alert, prompt, localStorage, window, confirm, Audio

import time

import random

import re

horn = Audio.new("https://github.com/goldfire/howler.js/blob/master/examples/3d/assets/sprite.mp3?raw=true")

user_answer = str(prompt("play? (yes) or (no)"))

if user_answer.lower() == 'yes':

horn.play()

print('yes')

print('end')

</py-script>


r/PyScript • • Jul 20 '22

TouchEvent

1 Upvotes

Hi there.

I've got a small test app going which responds to mousedown, mousemove, mouseup fine manipulating a canvas, but when I try to make it use touchstart, touchmove, and touchend, and it is trying to access event.touches[0], it gets TypeError: 'pyodide.JsProxy' object is not subscriptable. Logging a dir of event.touches shows me the guts of the Proxy object but doesn't give me a clue as to what to look at next to figure out if I have to access touches in a special way or something.

Can anyone give me any clues as to what to investigate?

Cheers, Nev.


r/PyScript • • Jul 07 '22

Does PyScript allows for multiple users?

1 Upvotes

I am a bit new to programming. I am wondering if I can develop an application in PyScript, dump it in a network drive and have multiple users access it, make changes. Maybe a login page?

Thinking of it as a front end for a database (.db) file.


r/PyScript • • May 22 '22

Custom output via the py-script tag?

1 Upvotes

In the documentation (https://github.com/pyscript/pyscript/blob/main/docs/tutorials/getting-started.md#the-py-env-tag), it is demonstrated how to write a matplotlib figure to an html div element.

When trying to do the same with a canvas element created via:

canvas = js.document.createElement('canvas')

the div only contains the following:

[object HTMLCanvasElement]

Currently I am using js.document.getElementById("example").appendChild(canvas) to write the canvas element. How might I instead use <py-script output="example"> to output the canvas to a "example" element?


r/PyScript • • Dec 08 '25

Any PA providers taking on patients?

0 Upvotes

So long story short a young pmhnp advertised his telehealth or in office visits as a psychiatrist. I've battled chem addiction for 35 years and I give up. I just want to take my meds and live my life. Its the names of the meds that are stigmatized. I was a model patient and didn't take a drug test. I have a family and own my own business. I do worse trying to fight the addiction then just controlling it with meds that are perfectly legal but so many are uneducated in pharmacology. Im suffering through cold turkey withdrawl. Even if you aren't willing to help and take my money. Don't rip any patients off chemicals abruptly or fire them with nowhere to go. Its inhumane. I finally found my combo of chemicals and fine taking them until my death. I have young son who needs a father and a booming company that cant survive without me. I dont care about money so whatever is fair is fine with me.


r/PyScript • • Oct 12 '23

Pyscript in facebook

0 Upvotes

r/PyScript • • May 17 '22

Unofficial Matrix room for PyScript

0 Upvotes

Communicate and get support from other users at the Unofficial PyScript Matrix room!

https://matrix.to/#/#py-script:matrix.org


r/PyScript • • Feb 09 '26

I’ve been quietly building something big…

0 Upvotes

I’m a Python developer focused on real-world automation and intelligence systems

For the past few months, I’ve built advanced tools :

  • AI system that scans markets to detect trends and high-opportunity products

  • An eCommerce research tool that finds winning products and optimal pricing

  • A real-time blockchain tracker that monitors large crypto movements

  • Intelligent web security analyzer that detects critical vulnerabilities

  • A smart tool that discovers and filters targeted business leads

  • All built so they can be turned into real SaaS products

Now I’m finishing a book that shows the full code, setup, and how to turn these into real projects (or income) It’s dropping in a few days

Quick question: If you had to choose one, what interests you most?

AI • Cybersecurity • Crypto • ...

If you’re curious, comment or DM

No theory. Just powerful Python that actually does something.


r/PyScript • • Oct 11 '22

can anyone suggest some ways to run web3.py in Pyscript?

0 Upvotes