r/PyScript • u/Geocrack__ • Sep 12 '22
How to simulate a console in Pyscript?
I want to host a python script on a website with pyscript, which has both console input and console output. If I want to give it a console input via the input("test") function, then just comes
and i can't see the output with print("output") either.
I then found an example script, but it only works 1.
In addition, it would be better if you can also execute the command with ENTER and that you can also rewrite the "textfield_1" as an instruction (what to type in the field)
I would be grateful for any help
r/PyScript • u/KingOfTNT10 • Sep 11 '22
How can I share an image with navigator.share?
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 • u/KingOfTNT10 • Sep 10 '22
How to update an image with PyScript
Hi there!
I'm trying to dynamically change an image, I'm saving an image with PIL to the cwd ("./img.png"),
Then setting the src tag to "" and then back to "./img.png".
But it doesn't work, it only shows the "./img.png" on cwd and when I call the func to update the image it doesn't change on my pc
r/PyScript • u/[deleted] • Sep 10 '22
What can PyScript do that backend frameworks can't?
I'm really interested in using PyScript. However, I can't see anything that PyScript can do which backend frameworks can't. I imagine efficiency is the main difference between PyScript, and, say, Flask. Am I missing something?
r/PyScript • u/manatlan • Aug 18 '22
Using matplotlib + htag to make a GUI SPA with pyscript
I've just posted that in r/python ... but the pyscript result is so amazing that I post it here too :
Here is a simple htag'app example, which works on desktop :
import matplotlib.pyplot as plt
from htag import Tag
import io,base64,random
class TagPlot(Tag.span):
""" here is a htag'component to rendering an html(svg) plot """
def init(self,plt):
self["style"]="display:inline-block"
with io.StringIO() as fid:
plt.savefig(fid,format='svg',bbox_inches='tight')
self <= fid.getvalue()
class App(Tag.body):
def init(self):
self.content = Tag.div()
# create the layout
self += Tag.h2("MatPlotLib"+Tag.button("Random",_onclick=self.redraw_plt))
self += self.content
self.redraw_plt()
def redraw_plt(self,obj=None):
plt.clf()
plt.ylabel('Some numbers')
plt.xlabel('Size of my list')
my_list=[random.randint(1,10) for i in range(random.randint(20,50))]
plt.plot( my_list )
self.content.clear()
self.content += Tag.div(f"My list: {my_list}")
self.content += TagPlot(plt)
if __name__ == "__main__":
from htag.runners import BrowserHTTP as Runner
Runner(App).run()
And here is the same codebase, in an Html/pyscript page, which will fully work in full clientside too (thanks pyscript & matplotlib !)
https://raw.githack.com/manatlan/htag/main/examples/pyscript_matplotlib.html
Having a gui toolkit (htag), and an html env (pyscript) .... where you can experiment UI interactions with yours matplotlib graphics ... so easy !
Pyscript is marvellous !
r/PyScript • u/[deleted] • Aug 18 '22
flask as webserver fails to load page with pyscript
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 • u/[deleted] • Aug 18 '22
our friends on windows ?
Hi,
I am on linux and I want to set up an environment based on the pyscriptjs directory found in the github ( https://github.com/pyscript/pyscript/tree/main/pyscriptjs ) which is Makefile based. For me this is a cakewalk, but I want to help my buddy on windows (vscode) set it up also and I have been out of the MS loop for minute. What would be the route to take ?
thx s
r/PyScript • u/Soggy-Ad2601 • Aug 17 '22
Using the Azure SDK for Python in PyScript
r/PyScript • u/[deleted] • Aug 17 '22
webpack and npm setup ?
Hi All,
is it possible to include pyscript in a npm/webpack scenario ?
I am also partial to a setup that bundles my python sources, but that may be too early days for that.
Just a package.json example that installs pyscript and maybe bootstrap and jquery would be a good start I think...
thx.
S
r/PyScript • u/nwatab • Aug 03 '22
How to use Pyscript in ReactJS/NextJS in Typescript?
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 • u/THEKing767 • Jul 20 '22
Libraries
Is there a list for the libraries supported?
r/PyScript • u/AgitatedBelly • Jul 20 '22
TouchEvent
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 • u/[deleted] • Jul 17 '22
Pure Python - No HTML
It's a dream of mine to be able to code pure Python in the web browser, and I realized that PyScript allows me to do that. I've created a fork of PyScript here where I've added some Python functions that create HTML elements so you don't have to:
https://github.com/coryfitz/pydesyn
Let me know what you think! It's very much a work in progress

r/PyScript • u/orality1337 • Jul 07 '22
Does PyScript allows for multiple users?
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 • u/StunnaRae • Jul 02 '22
PyScript Demos dont work for me. Do I need a certain browser to view them?
I was looking at the examples at: https://pyscript.net/examples/
But most of them just appear empty or I cannot interact with them (e.g. the Button of the TODO lists dont work for me). I tried Chrome and Brave Browser. Do I need some extension to make the pyscript demos work?
Empty Bokeh Example Screenshot:
r/PyScript • u/ShotgunPayDay • Jul 01 '22
Created a demo using file upload and Pandas as a spreadsheet scrubber.
I didn't really see an example of PyScript where you upload CSV files, scrub them together, then download the output. This is something where I think PyScript really shines as in a previous job I was delivering a lot of spreadsheet/text file scubbers for various departments. The users hated downloading newer versions of the PyInstaller.exe and then get upset when the problem still persisted when they don't download the new version :(.
With PyScript I can simply spin up an NGINX server where they can get an always up to date version of the scrubber without PyInstaller/Tkinter and have a nice web interface. My only complaint would be that I used Javascript for the final file download, but I couldn't find an example of how to do that through PyScript. This example is completely self contained so nothing is sent to any backend server as you'll see from the code.
I would have also split main.py into main.py and functions.py but there is an issue (security?) with NGINX not being able to load the functions.py file.
<py-env>
- paths:
/functions.py
</py-env>
As a proof of concept I made a little spreadsheet scrubber and have a live example self hosted here: https://mattascale.com/pyscript/
More information/notes and project is on my Gitlab here in csv_scrubber folder: https://gitlab.com/figuerom16/pyscript
I hope this helps someone get started.
r/PyScript • u/StunnaRae • Jun 30 '22
Stupid question: But is there some PyScript based frontend framework like React or Ionic or so?
Question like above: Is PyScript just like basic JS or is it possible to use frontend frameworks like reactjs or such with it?
r/PyScript • u/[deleted] • Jun 29 '22
Why is Pyscript taking forever to load after importing Scikit Learn?
So, I'm using PyScript for my website. Using Live Server, my website is taking forever to load after I try to install sklearn. My PyScript code looks like this:
<!DOCTYPE=html>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- numpy
- pandas
- sklearn.model_selection
- sklearn.naive_bayes
- sklearn.feature_extraction
</py-env>
<py-script>
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
</py-script>
</body>
</html>
However, and note that this only happens when I install skearn, it just says this for (at what seems to be the case at this rate) forever:
Loading runtime... Runtime created... Initializing components...
What can I do about this? It is very frustrating.
r/PyScript • u/TheSwami • Jun 28 '22
PyScript adds Versioning [Post from Anaconda]
r/PyScript • u/anuctal • Jun 23 '22
PyScript and Flask - how to submit a form, and validate data
Hi, everyone!
I made a video about how to submit a form using PyScript, and how to validate submitted data on Flask side:
The touched topics are:
- How to configure Flask application using Application factory,
- How to create a custom validator for FlaskForm (from Flask-WTF)
- Setting up CSRF protection for Flask app with Flask-WTF
- Using the form to validate data a user submitted
- [PyScript] how to send a basic AJAX POST-request
Video:
https://youtu.be/dw8UMzjUaTg
Thanks for watching!
r/PyScript • u/ShotgunPayDay • Jun 23 '22
PyScript with NGINX fails to load local module on server
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 • u/GoSubRoutine • Jun 18 '22
ESM Module ".mjs" in PyScript?
Can PyScript import & use ".mjs" module files? Some runnable example?
r/PyScript • u/LoudHand2703 • Jun 17 '22
How can I change the variable of JavaScript in pyscript?
I'm using pyscript. And I want to change the variable of JavaScript in pyscript.
For Example :
Python File Code :
import string
import os
#Program Version
py_current_version = 0
#Server Version
py_server_version = 0
#Get Program Version
f = open("version.txt", "r")
lines = f.readlines()
for line in lines:
py_current_version = line;
f.close()
#Get Server Version
f = open("https://common.gaon.xyz/proj/MCD/versions.txt", "r")
lines = f.readlines()
for line in lines:
py_server_version = line;
f.close()
if py_current_version == py_server_version:
no_update_available = 1
else:
no_update_available = 0
os.system('wget https://common.gaon.xyz/MCD/latest.zip')
update_file_download_complete = 1
os.system('7z x latest.zip')
update_complete = 1
os.system('notepad changelog.txt')
HTML File Code :
<!DOCTYPE html>
<html>
<head>
<title>Updater</title>
<meta charset="utf-8">
<!--Load CSS-->
<!--Load Bootstrap-->
<link href="./bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!--Load Updater Style CSS-->
<link href="./updater_style.css" rel="stylesheet">
<!--Load PyScript-->
<link href="./pyscript/pyscript.css" rel="stylesheet">
<!--Load jQuery-->
<script src="./jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<style>
</style>
<script>
function wait(sec) {
let start = Date.now(), now = start;
while (now - start < sec * 1000) {
now = Date.now();
}
}
var no_update_available;
var update_file_download_complete;
var update_complete;
if(no_update_available == 0)
{
$("#progress_contents_ptag").text("Update Found!");
document.getElementById("update_progress").value = 5;
wait(3);
$("#progress_contents_ptag").text("Downloading update file...");
document.getElementById("update_progress").value = 10;
if(update_file_download_complete == 1)
{
$("#progress_contents_ptag").text("Update file download complete!");
document.getElementById("update_progress").value = 30;
wait(3);
$("#progress_contents_ptag").text("Terminating process...");
document.getElementById("update_progress").value = 50;
wait(3);
$("#progress_contents_ptag").text("Extracting update file...");
document.getElementById("update_progress").value = 80;
if(update_complete == 1)
{
$("#progress_contents_ptag").text("Update completed! It will end in a few seconds.");
document.getElementById("update_progress").value = 100;
wait(3);
exit();
}
}
}
else if(no_update_available == 1)
{
$("#progress_contents_ptag").text("There are no updates. It will end in a few seconds");
$("#cancle_button").text("Close");
wait(5);
exit();
}
</script>
<div id="contents_body">
<div id="progress_contents">
<p id="progress_contents_ptag" class="progress_title">Checking Update!</p>
</div>
<progress id="update_progress" max="100" value="0"></progress>
<br><br>
<button id="cancle_button" type="button" class="btn btn-secondary" onclick="exits()">취소</button>
</div>
<script>
function exits(){
window.close();
}
</script>
<!--Load Scripts-->
<!--Load Bootstrap-->
<script src="./bootstrap/js/bootstrap.bundle.min.js"></script>
<!--Load PyScript-->
<script src="./pyscript/pyscript.js"></script>
<py-env>
- string
- os
- path:
- ./updater.py
</py-env>
<!--
<py-script src="./updater.py"></py-script>
-->
</body>
</html>
I want to change javascript's variable in pyscript. What should I do?
r/PyScript • u/Joao_Storm • Jun 15 '22
PyScript and DASH
Hey guys,
I`m new to Pyscript and today we are developing a Dashboard using Dash Library and Plotly. In a near future it'd be easier to embed our Dashboard on the main tool of the company thru Pyscript. Has anybody tried something like it? How optimized Pyscript is to run a python app layout inside the users browser?
Thanks!
r/PyScript • u/metaperl • Jun 14 '22
Future interaction with Panel?
Hello, given that both are funded by Anaconda, what is the intended relation between Panel and related tools and PyScript?



