







print(cars['speed'])

cars.values() fails is that cars is a list of 10 things, and each of those things is a dict. But cars itself is still a listfor loop, you should see a list of 10 things (contained with square brackets, separated by commas), and each of those things will be a small dict

for car in cars:
print(car[‘speed’]) (edited)

for car in cars:
print(car['speed'])




.title() is a method for string
https://www.w3schools.com/python/ref_string_title.aspfor brand in brands:
print(brand.title())






















my_variable = some expression, Python evaluates the right hand side (that is, does all the operations you've written out) and assigns the result to the variable named on the left hand side. In your case, the operation is the action of the "f-string" on the template. (The technical name is "literal string interpolation".) (edited)ticket = f'The ticket is {fee}', it does all the operations on the right hand side (resulting in, at first, the "The ticket is "), then sets the variable ticket to reference that newly created string. (edited)def get_ticket_msg(fee):
return f'The ticket is {fee}'
#...
if int(message) < 3:
print(get_ticket_msg('free'))
elif int(message) <= 12:
print(get_ticket_msg('$10'))
elif int(message) <= 999:
print(get_ticket_msg('$15'))

def get_ticket_msg(fee):
return f'The ticket is {fee}'
#...
if int(message) < 3:
print(get_ticket_msg('free'))
elif int(message) <= 12:
print(get_ticket_msg('$10'))
elif int(message) <= 999:
print(get_ticket_msg('$15')) 
data = {}
def contains(str, chars):
for i in chars:
if str.find(i) != -1:
return i
return False
print("Please Insert Your Equations")
while True:
exp = input()
op = contains(exp, ['+', '-', '*'])
if op:
expression = ''
ops = exp.split(op)
op1 = ops[0].strip()
op2 = ops[1].strip()
try:
expression += data[op1]
except KeyError:
expression += op1
expression += op
try:
expression += data[op2]
except KeyError:
expression += op2
try:
print(eval(expression))
except NameError as ne:
print(ne)
elif exp.find('='):
try:
tmp = exp.split('=')
key = tmp[0].strip()
value = tmp[1].strip()
data[key] = value
except:
print("invalid operator")
exp contains “=“ : find the value of the expression to the right of the equals sign (using the logic you already have for applying an op to variables or numbers), then assign that value the the variable named on the left hand side




while True:
x = input('enter variable: ')
reset = 0
data = {x: reset}
#inputnum1 = int(input("What number do you want to add? "))
while True:
inputop = input("Please Choose Your Operator: + or - or *: ")
inputnum2 = int(input("What number do you want to add? "))
if inputop == "+":
reset.append( + inputnum2)
elif inputop == "-":
reset.append( - inputnum2)
elif inputop == "*":
reset.append( * inputnum2)
else:
print("Invalid Operator! Please Try Again with a Valid Operator ")
answer1 = input("Do you want to do another calculation? ")
if answer1 == "NO" or answer1 == "No" or answer1 == "no" or answer1 == "N" or answer1 == "n":
print(*reset)
break
y = input('enter variable to get: ')
print(*data[y])
answer2 = input("Do you want to create another register/variable?")
if answer2 == "NO" or answer2 == "No" or answer2 == "no" or answer2 == "N" or answer2 == "n":
break
print("Loop Ended")


data?

data[key] = my_new_value




data[key] = my_new_value 







print() adds a newline character to the end of whatever you give it. This makes the output skip down to the start of the next line. By providing an end= argument, you tell print to add something else to the end instead.end=‘’ to just continue on the same line, but you could do something like end=‘\t’ to add a tab character at the end, or even something goofy like print(‘Hello’, end= ‘ World.) (edited)return in this case 

describe_city as a function, it’d be easy for a slip of the finger ti type dec-tab and allow it to autocomplete, VS code might guess you want the decimal class from unicodedata, autocomplete that and add the import at the top.
I find this feature is useful about 25% of the time, and a pain the other 75%

describe_city as a function, it’d be easy for a slip of the finger ti type dec-tab and allow it to autocomplete, VS code might guess you want the decimal class from unicodedata, autocomplete that and add the import at the top.
I find this feature is useful about 25% of the time, and a pain the other 75% 

ones there are referring to newline characters, the string of bytes which tells an editor/terminal/word processor/etc to skip down to the next line.
What the author is pointing out there is that the lines in the file already contain newline characters at the end, and that when you print something, by default print adds a newline character at the end. So when you run the sample code there without rstrip(), you see something like this: (edited)print(line.rstrip()) to remove the original newline from each line of the file before trying to print, so the lines only have a single newline at the end, added by print()


ones there are referring to newline characters, the string of bytes which tells an editor/terminal/word processor/etc to skip down to the next line.
What the author is pointing out there is that the lines in the file already contain newline characters at the end, and that when you print something, by default print adds a newline character at the end. So when you run the sample code there without rstrip(), you see something like this: (edited)







pi_digits.txt file you showed above















json.JSONDecoderError
You could also read the file before decoding it

json.JSONDecoderError
You could also read the file before decoding it 


with instead of without


class someClass:
def __init__(self):
self.sharedVariable = 2
def somefunction(self):
print(self.sharedVariable) # will be printed as we are using self
localVariable = 2 # local variable (not shared)
def someFunction2(self):
print(localVariable) # will give error as localvariable is not defined
# print(self.localVariable) # will work if you share the variable in someFunction by typing self.localVariable = 2

class someClass:
def __init__(self):
self.sharedVariable = 2
def somefunction(self):
print(self.sharedVariable) # will be printed as we are using self
localVariable = 2 # local variable (not shared)
def someFunction2(self):
print(localVariable) # will give error as localvariable is not defined
# print(self.localVariable) # will work if you share the variable in someFunction by typing self.localVariable = 2 











self.ship = Ship(self): at that line self is a reference to AlienInvasion, which is passed to the constructor of Ship.


self.ship = Ship(self): at that line self is a reference to AlienInvasion, which is passed to the constructor of Ship. 

if/elif, you enter in ONLY ONE of the cases. As soon as the first checked condition is true, you enter that branch and you don't bother checking the rest.
With a sequence of if/if, you check all conditions, and potentially enter all of them.
For the update case, the difference is "what happens if the user is pressing both the right and left keys together"? If you use if/elif, you enter only the first case (and thus the ship moves right), if you use if/if you enter both cases (and thus the ship doesn't move, since you do x += 1 and then x -= 1if/elif in the _check_events() method? In this case you already know that only at most one of the various conditions can be true (because a single event cannot be e.g. KEYDOWN and KEYUP at the same time), so an if/elif is preferable (although in this precise case, an if/if would work as well -- but not in general. In particular, if you have an if/elif/elif/.../else chain, then it has a very different meaning than an if/if/if/else chain)

if/elif in the _check_events() method? In this case you already know that only at most one of the various conditions can be true (because a single event cannot be e.g. KEYDOWN and KEYUP at the same time), so an if/elif is preferable (although in this precise case, an if/if would work as well -- but not in general. In particular, if you have an if/elif/elif/.../else chain, then it has a very different meaning than an if/if/if/else chain) 

the other question is: "why did they use if/elif in the _check_events() method?if/if and it would work fine

if/if and it would work fine 


__str__() method to return self.msg and then use print(Go())

__str__() method to return self.msg and then use print(Go()) 

aaa = Go()
print(aaa.msg)





















replace(' it "closes" the fstring

f'{msg.replace("i", "i")}'
Or the other way around


replace(' it "closes" the fstring 



oninput method of the slider send a request back to the server with it's value, then have the server handle that request and do something with it. Here's a brief example.slider.oninput and the server's new do_POST method are the things to look at. I also commented out some Raspberry Pi-specific things for my testing, since I'm not on a Pi at the moment, but uncomment them at your leisure 





page.html somewhere else or call it something else, change the path here (line 41)
with open('page.html', 'r') as fp: (edited)






- in front of the value:
For example:>>> x = 42
>>> print(-x)
-42servo1.angle = -int(value/364))

- takes care of that too!
>>> x = -1000
>>> print(-x)
1000-1servo1.angle = -int(value/364)) will make all positive values into negative, and all negative values into positive



























import itertools
numbers = [1,2,3,9]
print(list(itertools.combinations(numbers, 3)))iter, even though that does something quite different https://docs.python.org/3/library/functions.html#iter



import itertools
numbers = [1,2,3,9]
print(list(itertools.combinations(numbers, 3))) 






pip install -e <projectname>
-estands for editable. Then each update to the project is directly reflected in your virtualenv (if you're using one)





/unstable (main branch) is also on 0.22.1 by default for now... but someday the Pyodide 0.23 PR will be mergable 

/unstable (main branch) is also on 0.22.1 by default for now... but someday the Pyodide 0.23 PR will be mergable 




<!DOCTYPE html>
<html lang="en">
<head>
<title>Globe.gl Arcs Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="https://pyscript.net/releases/2023.03.1/pyscript.css" />
<script defer src="https://pyscript.net/releases/2023.03.1/pyscript.js"></script>
<script src="//unpkg.com/globe.gl"></script>
</head>
<body>
<py-script src="./main.py"></py-script>
<div id="globeViz"></div>
</body>
</html>
main.py
import js
from js import Globe
Globe().globeImageUrl(
'//unpkg.com/three-globe/example/img/earth-night.jpg'
)(js.document.getElementById("globeViz")) (edited)






pre element with a class py-error.
Am i wrong in the understanding that python errors go to stderr?

pre element with a class py-error.
Am i wrong in the understanding that python errors go to stderr? stderr in pyodide is a bit weird and not always possible to catch, inevitably ending up in devtools console as error but we also catch at the main/window level and show errors on the page. In PyScript Next you can disable the error via py-config or config attribute by writing plugins = ["!error"] if that bothers you, but also PyScript Next has no terminal (yet).
stderr attribute of a py-script tag to route things written to stderr to a DOM element with a matching ID.
2022.12.1.dev.
Good to know, thanks for all that info. I'll try out the stderr attribute.
I have a weird scenario actually. I am working on a react app which runs in an iframe on another app platform. So the py-script tag runs twice (still trying to figure out why), but based on another suggestion on this discord, I am running the python code using window.self.pyscript.interpreter.interpreter.runPythonAsync(code);. Does this also have all the stderr connections or only the py-script tag?
stderr attribute you would need to place the code inside a <py-script> tag; but you can also grab the Pyodide runtime itself (which is what pyscript.interpreter.interpreter is a reference to) a use the stdStderr function to provide your own handler: https://pyodide.org/en/0.23.2/usage/api/js-api.html#pyodide.setStderrrunPythonAsync, so may or may not be useful for your use case/latest link right now points to what is actually 2023.05.1 
from pyscript import when, which was only added in 2023.05.1

stderr attribute you would need to place the code inside a <py-script> tag; but you can also grab the Pyodide runtime itself (which is what pyscript.interpreter.interpreter is a reference to) a use the stdStderr function to provide your own handler: https://pyodide.org/en/0.23.2/usage/api/js-api.html#pyodide.setStderr window.self.pyscript.interpreter.interpreter.runPythonAsync(code); and sent the error to the xterm instance.

window.self.pyscript.interpreter.interpreter.runPythonAsync(code); and sent the error to the xterm instance. window.self.pyscript in JS means pyscript ... no need for window.self before, but I am not adding much to the issue/solution, I suppose, just spotted a double redundant reference 

window.self.pyscript.interpreter.interpreter.runPythonAsync(code); and sent the error to the xterm instance. 






input() inside a worker
npm run start reaching http://localhost:8080/test/terminal.html https://github.com/pyscript/pyscript/pull/1696




turtle.py with pyscript, so that import turtle works out of the box.
It's not super clear what is the best way to do it, because currently the stdlib is bundled&downloaded directly by pyodide

turtle.py with pyscript, so that import turtle works out of the box.
It's not super clear what is the best way to do it, because currently the stdlib is bundled&downloaded directly by pyodide 


<div id="app">
<p>Translate English into Pirate speak...</p>
<input type="text" name="english" id="english" placeholder="Type English here..." />
<button py-click="translate_english">Translate</button>
<div id="output"></div>
<script type="py" src="./main.py" config="./pyscript.toml"></script>
</div>

main.py file we're eventually interested in, I think 
import arrr
from js import document
def translate_english(event):
input_text = document.querySelector("#english")
english = input_text.value
output_div = document.querySelector("#output")
output_div.innerText = arrr.translate(english)



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Arrr - Piratical PyScript</title>
<link rel="stylesheet" href="https://pyscript.net/snapshots/2023.09.1.RC2/core.css" />
<script type="module" src="https://pyscript.net/snapshots/2023.09.1.RC2/core.js"></script>
</head>
<body>
<h1>Arrr</h1>
<p>Translate English into Pirate speak...</p>
<input type="text" id="english" placeholder="Type English here..." />
<button py-click="translate_english">Translate</button>
<div id="output"></div>
<script type="py" src="./piratical.py" config="./piratical.toml"></script>
</body>
</html>
import arrr
from js import document
def translate_english(event):
input_text = document.querySelector("#english")
english = input_text.value
output_div = document.querySelector("#output")
output_div.innerText = arrr.translate(english)
packages = ["arrr"]from js import document should be instead from pyscript import document but from main, everything works as expected anywayindex.html second one is piratical.py and third one is piratical.toml





from pyscript import document
def printTutorial(event):
input_text = document.querySelector("#input")
#input_text.value
if input_text.value == "yes":
output_div = document.querySelector("#output")
output_div.innerText += "no this is not yes" + "\n"
input_text.value = ""












from pyscript import document to select a <button> element with an ID and trigger from the onclick action?

from pyscript import document to select a <button> element with an ID and trigger from the onclick action? document.getElementById('your-button').click() ?

document.getElementById('your-button').click() ? 
onclick instead you can document.getElementById('your-button').addEventListener('click', your_click_handler) where your_click_handler receives an event object with event things

var elements = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
What would be PyScript version using from pyscript import document button_elements = document.getElementsByClassName('btn')
def button_action_call(button):
button_id = button.getAttribute("id")
for button in button_elements:
button.addEventListener('click', button_action_call, False)
Thoughts, suggestions welcome

var elements = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
What would be PyScript version using from pyscript import document button_elements = document.getElementsByClassName('btn')
def button_action_call(button):
button_id = button.getAttribute("id")
for button in button_elements:
button.addEventListener('click', button_action_call, False)
Thoughts, suggestions welcome <button id="hi" class="btn">Hello!</button>
<button id="bye" class="btn">Goodbye!</button>
<script type="py">
from pyscript import window, document
from pyodide.ffi import create_proxy #works in both Pyoide and Micropython
elements = document.getElementsByClassName("btn")
def handler(evt):
id = evt.target.getAttribute("id")
window.alert(id)
for el in elements:
el.addEventListener('click', create_proxy(handler))
</script>@when decorator:
from pyscript import when
@when('click', '.btn')
def handler(evt):
id = evt.target.getAttribute("id")
window.alert(id) (edited)
XMLHttpRequest js method working and sending an API request to a simple's Flask app through ngrok
Now it's just sorting MQTT on the MicroController and we should have the MeArm controller working 
create_proxy method which worked perfectly .. Thanks .. 

@when decorator:
from pyscript import when
@when('click', '.btn')
def handler(evt):
id = evt.target.getAttribute("id")
window.alert(id) (edited)

@whenever decorator that would, via a mutation observed, function dynamically. Hasn’t been high priority, but perhaps soon.

@whenever decorator that would, via a mutation observed, function dynamically. Hasn’t been high priority, but perhaps soon. 

create_proxy method which worked perfectly .. Thanks .. 

<script> tag that points to core.js have type="module"?
<script type="module" src="https://pyscript.net/releases/2023.12.1/core.js"></script>

wiki = Wiki(), which should try to create an object for wikipedia, as that's what it defaults to, i am met with a whole lot of errors

ImportError: Cannot connect to HTTPS URL because the SSL module is not availablessl to your packages in py-config and see what happens. But, since it seems urllib3 is in play, you should consider adding pyodide-http to yout config as well and patching that library https://github.com/koenvo/pyodide-http

ssl to your packages in py-config and see what happens. But, since it seems urllib3 is in play, you should consider adding pyodide-http to yout config as well and patching that library https://github.com/koenvo/pyodide-http 

ImportError: Cannot connect to HTTPS URL because the SSL module is not available 






pyodide_http to your packages list in your pyscript.toml/config file and then add the following at the top of your python code.
import pyodide_http
pyodide_http.patch_all()

pyodide_http to your packages list in your pyscript.toml/config file and then add the following at the top of your python code.
import pyodide_http
pyodide_http.patch_all() 










var elements = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
What would be PyScript version using from pyscript import document button_elements = document.getElementsByClassName('btn')
def button_action_call(button):
button_id = button.getAttribute("id")
for button in button_elements:
button.addEventListener('click', button_action_call, False)
Thoughts, suggestions welcome 

pyodide_http.patch_all() it seems to give 2 errors in the console



settings.json, if you want to use numpy, you'd have an entry something like this:
{
"packages": ["numpy"]
}
....and you'd reference the settings like this:
<script type="py" src="./main.py" config="./settings.json"></script>

settings.json, if you want to use numpy, you'd have an entry something like this:
{
"packages": ["numpy"]
}
....and you'd reference the settings like this:
<script type="py" src="./main.py" config="./settings.json"></script> 


















































from pyscript import display,HTML
import html2text
html_content = '<html>hello</html>'
text_content = html2text.html2text(html_content)
print(repr(text_content))
print(text_content.strip())
print(text_content.strip())
print(text_content.strip())
yields:
'hello\n\n'
hello
hello
hello

from pyscript import display,HTML
import html2text
html_content = '<html>hello</html>'
text_content = html2text.html2text(html_content)
print(repr(text_content))
print(text_content.strip())
print(text_content.strip())
print(text_content.strip())
yields:
'hello\n\n'
hello
hello
hello 








from package import somename into your Python code.





from package import somename into your Python code. 
math in the config file at all - since it's in the Python standard library https://docs.python.org/3/library/index.html and (almost) all of that is installed in Pyodide by default.

math in the config file at all - since it's in the Python standard library https://docs.python.org/3/library/index.html and (almost) all of that is installed in Pyodide by default. 









getAttribute method on HTML elements to get their html attributes like bid https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributedef addval(event) … event.target.getAttribute(bid) or similar

getAttribute method on HTML elements to get their html attributes like bid https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute 

packages key installs packages from PyPI, or the Pyodide repo, or wheels that you’ve built yourself that are available at a URL. More info here: https://pyscript.recipes/2024.1.1/basic/installing-packages/files key in pyconfig is the way to do this, though it’s a lot to enumerate https://pyscript.github.io/docs/2024.1.3/user-guide/configuration/






./flaskserver/app{FROM} though



__init__.py is not found and your server produces a 404 with HTML content 










ALTER TABLE prod ... as example.






















fun prints the value and return nothing ... or better, if it returns implicitly what print returns that's a None ... you are double printing in short.c instead or don't print(fun(a, b)) just fun(a, b) ... this is the same in native Python.

fun prints the value and return nothing ... or better, if it returns implicitly what print returns that's a None ... you are double printing in short. 

print in fun, return the value insteaddef fun(x,y):
c = f"{int(x)+int(y)}"
return c

print in fun, return the value instead 

fun still return a value if you want to assign it or print it outside the func ... this is how Python works.

def fun(x,y):
c = f"{int(x)+int(y)}"
print(c)
print(x)
print(y)
return c

def fun(x,y):
c = f"{int(x)+int(y)}"
print(c)
print(x)
print(y)
return c 





























sys.stdout.buffer.write( b"\x1b7\033]1337;File=inline=1:")
sys.stdout.buffer.write( base64.b64encode(img.read()) )
sys.stdout.buffer.write( b"\a\x1b8")
sys.stdout.flush()


from rich.console import Console as RichConsole
rich._console = RichConsole(color_system="256")








pip in PyScript, there's micropip in Pyodide and mip in MicroPython but these are not directly exposed to the running Python env

domain_pattern = r"^(?![0-9]+$)(?!-)(?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9]\.)+(?:[a-zA-Z]{2,})$"
domain_pattern = r"^[a-zA-Z0-9-]{1,63}\.[a-zA-Z]{2,}$" and it stop giving errors but for some wired reason it won't match even on valid input inp=document.getElementById("inp")
if(re.match(domain_pattern,str(inp.value))):

domain_pattern = r"^(?![0-9]+$)(?!-)(?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9]\.)+(?:[a-zA-Z]{2,})$" 



display shows content on the DOM, not the terminalprocess(code) to write code in the terminal but it might interaction but then again, I am not sure I understand what you are trying to do

display shows content on the DOM, not the terminal 
















def vertices(self, coordinates):
proxy = create_proxy(coordinates.astype(np.float32))
self._instance.vertices(proxy)
proxy.destroy() (edited)drawing.vertices = function(coordinates) {
let buffer = coordinates.getBuffer();
for (let i = 0; i < buffer.data.length; i += 2) {
this.vertex(buffer.data[i], buffer.data[i + 1]);
}
buffer.release();
coordinates.destroy();
}; (edited)
this.vertex to console.log, I don't see the performance tank. There must be some other JavaScript thing I don't understand at work here.

destroy() are necessary? How would I know if I had a memory leak in my code?



destroy() are necessary? How would I know if I had a memory leak in my code? destroy() , when available (i.e. it's not a thing in MicroPython) you should always invoke it. Alternatively you can use experimental_create_proxy = "auto" in your py-config and see how that goes and forget about all these details but when you are in charge, we all know explicit is better than implicit.














handleFile(event) does not run. The first statement in handleFile(event) is print("Function is running."). I did a Google search and cannot seem to find anything like this.
I'm on Windows 10 Home and using Pyscript.com account to make my test programs. I also turned off my Ad blocker for Pyscript.com. I also just signed up for Pyscript today. The Hello World program worked. This drag and drop program does not work. (edited)def handleFile(event):
print("Function is running. Please wait...")
# Get the dropped file object
dropped_file = event.target.files[0] # Get the file object.
# Access file information like name and size
file_name = dropped_file.name
file_size = dropped_file.size
# Process the file content (read as bytes)
file_content = dropped_file.read()
# Perform actions on the file content based on your needs
# (e.g., display information, upload to server)
print(f"File Name: {file_name}, Size: {file_size}")
# ... your processing logic here ...
print("This is main.py") # This runs.

handleFile(event) does not run. The first statement in handleFile(event) is print("Function is running."). I did a Google search and cannot seem to find anything like this.
I'm on Windows 10 Home and using Pyscript.com account to make my test programs. I also turned off my Ad blocker for Pyscript.com. I also just signed up for Pyscript today. The Hello World program worked. This drag and drop program does not work. (edited)handleFile as an event handler?
<!DOCTYPE html>
<html lang="en">
<head>
<title>DragDrop1</title>
<!-- Recommended meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- PyScript CSS -->
<link rel="stylesheet" href="https://pyscript.net/releases/2024.5.1/core.css">
<!-- This script tag bootstraps PyScript -->
<script type="module" src="https://pyscript.net/releases/2024.5.1/core.js"></script>
</head>
<body>
Drag the file to the area below and wait for a message.
You don't need to click a button or anything else.
<p/>
<input type="file" id="fileInput" onchange="handleFile(event)">
<p/>
<script type="py" src="./main.py" config="./pyscript.toml" terminal></script>
</body>
</html> (edited)name = "DragDrop1"
py-change attribute for attaching event handlers, instead of onchange
https://docs.pyscript.net/2024.5.1/user-guide/builtins/#html-attributes





py-change attribute for attaching event handlers, instead of onchange
https://docs.pyscript.net/2024.5.1/user-guide/builtins/#html-attributes 






handleFile(event) does not run. The first statement in handleFile(event) is print("Function is running."). I did a Google search and cannot seem to find anything like this.
I'm on Windows 10 Home and using Pyscript.com account to make my test programs. I also turned off my Ad blocker for Pyscript.com. I also just signed up for Pyscript today. The Hello World program worked. This drag and drop program does not work. (edited)











.remove() which is a standard API

.remove() which is a standard API 

remove() ... I don't know if latest PyDOM has that method, LTK seems to be fine there.

remove() ... I don't know if latest PyDOM has that method, LTK seems to be fine there. 


display has an append=True option by default, you pass append=False and it should clear/replace whatever was there before ... is this what you are asking? I am not sure I am following out of screenshots

display has an append=True option by default, you pass append=False and it should clear/replace whatever was there before ... is this what you are asking? I am not sure I am following out of screenshots 


config attribute that points at something like packages = ["matplotlib"] in it (if TOML)

display you are using as Python function, accepts an accpet=Flase which replaces the previous content


py-editor is not a py ... it's a different type, a different "beast", with a completely different environment ... you need to pass a config="./editor.toml" within that editor, the rest of the py scripts won't, and can't, also shouldn't, ever affect an editor



display() (out of interest).

display() (out of interest). 
display is just a Python-in-the-browser way of doing printdisplayimg src and insert it into the DOM.display.

display in IPython notebooks (they have a similar function).

display it, if you're in PyScript, you display it. If you're in "vanilla" Python you plot.show() it right..?

display..?




setup node where you can expose, override, or change the print function to have it do whatever you like if the file="element-id" is used, as example, so that you would display instead of using the builtin printprint(image, file="#css-selector")display where the intent is explicit.print(arg) in there and, if it's not a string, use display behind the scene ... maybe that's a bit better





print maybe we should think about improving the current state and use display behind the scene automagically? seems like other pakcages are able to do that (or not require print at all but I don't understand how that would work).















exec function https://docs.python.org/3.12/library/functions.html#exec and I think pyodide does something magic in there ... that's still a command you need to run as opposite of using display which doesn't need you to evaluate the whole thing ... it gives you more fine tuned control within the code you run.exec but I suppose these are smart enough to append to the body the latest image. You also have less control of where you want to show the image but regardless this is an interesting feature of pyodide

display has an append=True option by default, you pass append=False and it should clear/replace whatever was there before ... is this what you are asking? I am not sure I am following out of screenshots 

display("hello", append=False) (edited)

target= keyword if you want to stick the output somewhere specific instead of at the end of the doc (edited)display remains unchanged... (edited)

target= keyword if you want to stick the output somewhere specific instead of at the end of the doc (edited)










from pyscript import display ... what do you mean there's no display in the PyEditor? the pyscript namespace is there.

from pyscript import display ... what do you mean there's no display in the PyEditor? the pyscript namespace is there. script.code and script.code = "print(1 + 2)" as PyEditor script tag feature.

from pyscript import display ... what do you mean there's no display in the PyEditor? the pyscript namespace is there. 




<script type="mpy-editor">
import sys
from pyscript import display
display(sys.version, target="the_target", append=False)
</script>
<div id="the_target"></div>
I'd like to add that if that's the default behavior you want, you can create a setup node and override the print function to use display instead and the target you want as node to show things. (edited)

<script type="mpy"> is not there by accident so when bootstrap performance matters, feel free to use it.

<script type="mpy-editor">
import sys
from pyscript import display
display(sys.version, target="the_target", append=False)
</script>
<div id="the_target"></div>
I'd like to add that if that's the default behavior you want, you can create a setup node and override the print function to use display instead and the target you want as node to show things. (edited)<script type="mpy-editor" env="print-override" setup>
from pyscript import display
def print(what, target=None, append=False):
if target is None:
target = "the_target"
display(what, target=target, append=append)
</script>
<script type="mpy-editor" env="print-override">
import sys
print(sys.version)
</script>
<div id="the_target"></div> (edited)

<script type="mpy-editor">
import sys
from pyscript import display
display(sys.version, target="the_target", append=False)
</script>
<div id="the_target"></div>
I'd like to add that if that's the default behavior you want, you can create a setup node and override the print function to use display instead and the target you want as node to show things. (edited)






pypiserver in a service worker, so you can run pip on the frontend (as a teaching tool for pip). Not quite there yet, but it's been interesting to try. Using httpx's AsyncClient like pyscript.sw does is hugely helpful - most server clients assume the existance of threads

pyscript namespace ... it has no default target node because codemirror is a different thing as target, is where you want your code to be highltagted and worked on























<textarea>
<script>alert("nope")</script>
</textarea>
this just shows <script>alert("nope")</script> as is, there's no parsing and the only issue you might have is if your code includes a </textarea> but that's also true for inline scripts if the code includes </script> in it ... can you point me at the discussion around this textearea insecurity?display on occasions.

<textarea>
<script>alert("nope")</script>
</textarea>
this just shows <script>alert("nope")</script> as is, there's no parsing and the only issue you might have is if your code includes a </textarea> but that's also true for inline scripts if the code includes </script> in it ... can you point me at the discussion around this textearea insecurity? 











<script><script></script></script> breaks HTML parser so the answer is no but also it's likely you never want to do that








frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these.

frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these. 

frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these. 




frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these. 

parent you have security concerns. This is all about Web DOM best practices and security though, not much to do with PyScript or Python in general. Your goal, and that's usually mine too, is to achieve what you want to do. If security is OK and it works, I'd say job done?















import time
import pydirectinput
import keyboard
try:
# Wait for 5 seconds before starting key presses
time.sleep(5)
# Simulate pressing 'o' key multiple times with small delays
for _ in range(6):
pydirectinput.press('o')
time.sleep(0.1)
# Simulate pressing 'Page Up' key multiple times with small delays
for _ in range(3):
keyboard.press_and_release('page up')
time.sleep(0.1)
# Print end message after all key presses are done
print("end")
except Exception as e:
print(f"Error occurred: {e}")
Nothing works to use Page Up
Tried pyautogui and pydirectinput and running it as admin, everything is installed



import time
import pydirectinput
import keyboard
try:
# Wait for 5 seconds before starting key presses
time.sleep(5)
# Simulate pressing 'o' key multiple times with small delays
for _ in range(6):
pydirectinput.press('o')
time.sleep(0.1)
# Simulate pressing 'Page Up' key multiple times with small delays
for _ in range(3):
keyboard.press_and_release('page up')
time.sleep(0.1)
# Print end message after all key presses are done
print("end")
except Exception as e:
print(f"Error occurred: {e}")
Nothing works to use Page Up
Tried pyautogui and pydirectinput and running it as admin, everything is installed 












terminal attribute when you don't want a terminal? any particular reason for wanting but not seeing it?

terminal attribute when you don't want a terminal? any particular reason for wanting but not seeing it? 


terminal attribute. If you want to see prints on the page, use terminal attribute ... it's more about you deciding what you want. If your template can't decide if terminal attribute should be there or not, consider updating or changing template engine as that's a pretty simple to ask/demand from a templating engine?

terminal attribute. If you want to see prints on the page, use terminal attribute ... it's more about you deciding what you want. If your template can't decide if terminal attribute should be there or not, consider updating or changing template engine as that's a pretty simple to ask/demand from a templating engine? hide and show a terminal node ... the script has a target you can use to make it hiden or not so you can easily decide when it should be shown or not on the page, if SPA (Single Page Application) is what you are after.

hide and show a terminal node ... the script has a target you can use to make it hiden or not so you can easily decide when it should be shown or not on the page, if SPA (Single Page Application) is what you are after. 




onclick there, in the HTML ... to refer to Python functions, which I removed, as that's not valid and in conflict with when decorator ... there are other gotchas around the layout (<p> elements can't contain block elements and other things) but at least you can see that showing/hiding the terminal element is a terminal.element.hidden = True/False operation away. I hope this helps. (edited)

onclick there, in the HTML ... to refer to Python functions, which I removed, as that's not valid and in conflict with when decorator ... there are other gotchas around the layout (<p> elements can't contain block elements and other things) but at least you can see that showing/hiding the terminal element is a terminal.element.hidden = True/False operation away. I hope this helps. (edited)


@when event? I see it printing hello once per each click otherwise ...

@when event? I see it printing hello once per each click otherwise ... @when decorator, I don't see any mechanism to make it dispatch the event once and clean up ... when it comes to DOM methods though, you can pass {"once": True} as third and last argument https://pyscript.com/@agiammarchi/yellow-moon-copy/latest@when_once utility for this use case, as it's fairly common on the Web /cc @ntoll @Jeff Glass

@when decorator, I don't see any mechanism to make it dispatch the event once and clean up ... when it comes to DOM methods though, you can pass {"once": True} as third and last argument https://pyscript.com/@agiammarchi/yellow-moon-copy/latest 


once=True flag into the @when decorator..?

once=True flag into the @when decorator..? once is only one of the options we could pass, there are more https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options

once is only one of the options we could pass, there are more https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options 


@when should accept more named properties and we should provide identical behavior across interpreters. My feeling is that Pyodide does something special related to the proxy/callback life-cycle which is something harder to orchestrate manually on our side unless the experimental_proxy_auto flag is enabled so that we have automatic disposal of those functions once the related node doesn't exist anymore (it's garbage collected). Alternatively I can ask Pyodide folks if they'd be happy to add an extra optional parameter usable to add more Web standard features.













































ltk.proxy().
E.g. something like this: ltk.Input(self.shortname).on("change", ltk.proxy(lambda event: rename_color(event, self))). The proxty inside pyscript is detailed? here - https://docs.pyscript.net/2024.8.2/user-guide/ffi/

ltk.proxy().
E.g. something like this: ltk.Input(self.shortname).on("change", ltk.proxy(lambda event: rename_color(event, self))). The proxty inside pyscript is detailed? here - https://docs.pyscript.net/2024.8.2/user-guide/ffi/ 







ffi.to_js(reference)


js.Object.defineProperty()


window.thing = anyPythonThing btw, where from pyscript import window but you could also use window.Object.defineProperty(window, 'thing', { value: anyPythonThing }) although in latter case, if it's a callback, you might need pyscript.ffi.create_proxy there.




experimental_create_proxy = "auto" flag, you probably never need ever again to worry about this in Pyodide, while MicroPython uses that primitive out of the box so that don't need a special flag around it. (edited)

el = document.getElementById("test")
el.addEventListener("click", lambda e: print(e.type))
here you are telling the JS side of affair to add a listener that will print the event type (click) once clicked ... now, because there is no interoperability across PLs in the WASM to JS world. how does Pyodide know that such lambda can be destroyed from its own memory stack? In WASM, allocated memory to work is crucial so far so the more it's free, the better it is for your software not to crash or just keep growing RAM requirements over time ... so they confined a FinalizationRegistry orchestration in their ffi utilities to add listeners, but they are asking you to decide when that listener should be destroyed, which is only related to the lifecycle of that el reference, not only in Python, also in JS / DOM world. Without explicit proxy.destroy() that cannot be decided for a generic listener out there if nobody knows when it's going to be collected, they actually (imho) created another problem ... nobody knows, or care about, destroying proxies, so that the FinalizationRegistry automated dance would be better for everyone, because once that el is not existent anymore on the DOM, and that el reference can be collected on the Python side too, that listener would be automatically collected. They know that for the DOM ffi related API, but this pattern is actually all over the place, not just listeners, yet I haven't convinced them they should trust more the FinalizationRegistry and erase create_proxy and its expectations from their API as that causes more troubles than it solves, imho def addClick(css):
# el is locally scoped
el = document.querySelector(css)
el.addEventListener("click", lambda e: print(e.type))
# meaning, here el can be collected, without retaining
# a reference needed to exist on the JS/DOM side
# that lambda though ... exists until the `el` in the
# JS/DOM side is live or referenced
# so here Python flags el as collectable, but on the JS side
# that lambda must be invokable until the element exist


p.destroy() it

create_proxy has (known) no side-effects, in Pyodide it means "retain that thing until you decide it should not be retained anymore" ... which is cool and everything, but if you defined a timer in JS world? maybe that would never be called ... you define a listener? that should work until that related element exist ... you define any handler of any feature exposed to Python? same as DOM element listeners ... so here be careful, just using create_proxy is not a long-term, long-living, solution to anything, it actually puts more weight on your shoulders ... if you do use that a lot, I strongly suggest the config flag I've mentioned so that most (but not all) things would just work without you needing to even think about create_proxy wraps ... and "that's a wrap" (no pun intended).







create_proxy exists because otherwise it wouldn't be possible to break certain js to Python references manually so we do the reverse












pyscript-help and python-help suggests one is about help for pyscript and one is about help for python the language. If they were the same then there would only be one of them. I am surprised I have to write this down. Also I don't work here either - I'm just a committed user of pyscript.


pyscript-help and python-help suggests one is about help for pyscript and one is about help for python the language. If they were the same then there would only be one of them. I am surprised I have to write this down. Also I don't work here either - I'm just a committed user of pyscript. 









ulab package that gives you a bunch of Numpy like capabilities. We're currently discussing with Damien (i.e. 5mins ago I just pinged him an email about this very thing before checking discord 


from flask import Flask
import time
import board
import adafruit_dht
app = Flask(__name__)
@app.route("/")
dht = adafruit_dht.DHT11(board.D2)
while True:
try:
temperature = dht.temperature
humidity = dht.humidity
# Print what we got to the REPL
print("Temp: {:.1f} *C \t Humidity: {}%".format(temperature, humidity))
except RuntimeError as e:
# Reading doesn't always work! Just print error and we'll try again
print("Reading from DHT failure: ", e.args)
time.sleep(1)
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)


import adafruit_dht and not import adafruit_circuitpython_dht











mini-coi.js the proper way, just not as copy/paste script, it should be the first <script src="mini-coi.js"></script> tag on that HTML (and every other) and you'll be good to go with workers too






http://128.128.128.X agent to use that https://.... version and it has recognizable certificates, you're done, but it might be a bumpy ride.




--kiosk argument to not have it full screen








storage module. Can anyone offer advice ?
The docs say:
from pyscript import storage
store = await storage("my-storage-name")
and store will be a dictionary. This seems to be taking advantage of the hidden top level async that pyscript is called with. However I want to start the store and read values from within a class (specifically a reactive model class within the class which is the ltk.) So that each UI component can be independent of global variables.
I know I can't do an await inside an __init__ function. So what is the best way to get something working which would behave like this:
class Reactive_component(ltk.Model):
def __init__(self):
super().__init__()
self.store = await self.start_store()
async def start_store(self):
self.store = await storage("my-storage-name")
So I can then do reads and writes(syncs) to self.store.
I have seen a solution that adds a class method to an async_init alongside the __init__ like this
@classmethod
async def build(cls):
instance = cls()
await instance.async_init()
return instance
but as this would be called from inside the parent __init__ (from the ltk) I seem to be cascading these all the way to the top.
Is there another way - maybe using asyncio.run() or somesuch ?
(although asyncio.run cannot be called from a running event loop(I.e. inside an __init__)

storage module. Can anyone offer advice ?
The docs say:
from pyscript import storage
store = await storage("my-storage-name")
and store will be a dictionary. This seems to be taking advantage of the hidden top level async that pyscript is called with. However I want to start the store and read values from within a class (specifically a reactive model class within the class which is the ltk.) So that each UI component can be independent of global variables.
I know I can't do an await inside an __init__ function. So what is the best way to get something working which would behave like this:
class Reactive_component(ltk.Model):
def __init__(self):
super().__init__()
self.store = await self.start_store()
async def start_store(self):
self.store = await storage("my-storage-name")
So I can then do reads and writes(syncs) to self.store.
I have seen a solution that adds a class method to an async_init alongside the __init__ like this
@classmethod
async def build(cls):
instance = cls()
await instance.async_init()
return instance
but as this would be called from inside the parent __init__ (from the ltk) I seem to be cascading these all the way to the top.
Is there another way - maybe using asyncio.run() or somesuch ?
(although asyncio.run cannot be called from a running event loop(I.e. inside an __init__) read or an async write method or having an explicit await ref.init_storage() after initializing that ref. (edited)await the storage once on top of your module

read or an async write method or having an explicit await ref.init_storage() after initializing that ref. (edited)__main__) and that can also be imported to be used by amore complex UI that refers to them, and which in turn can be imported to even higher levels of hierarchy. If I define the access to store as a global in each I "think" I might be generating problems for myself. That is my only reason. For now I will continue with globals. Thanks for trying to help. Cheers...







<p id="csv"> tag. Here's the script for the tutorial in question:
import pandas as pd
from pyodide.http import open_url
url = 'list.csv'
df = pd.read_csv(open_url(url))
csv = Element('csv')
csv.write(df.head())
The problem is that it doesn't recognize the Element() function. I've searched for Element() in the API documents (whether pandas, pyscript, or other support sites), without success. Thanks. (edited)

<p id="csv"> tag. Here's the script for the tutorial in question:
import pandas as pd
from pyodide.http import open_url
url = 'list.csv'
df = pd.read_csv(open_url(url))
csv = Element('csv')
csv.write(df.head())
The problem is that it doesn't recognize the Element() function. I've searched for Element() in the API documents (whether pandas, pyscript, or other support sites), without success. Thanks. (edited)display utility in PyScript but also a fetch one ... synchronous API will fail on the main thread + we always run top-level await so that open_url sohuld likely not be used unless you are sure you can use it (i.e. in a worker)


<p id="csv"> tag. Here's the script for the tutorial in question:
import pandas as pd
from pyodide.http import open_url
url = 'list.csv'
df = pd.read_csv(open_url(url))
csv = Element('csv')
csv.write(df.head())
The problem is that it doesn't recognize the Element() function. I've searched for Element() in the API documents (whether pandas, pyscript, or other support sites), without success. Thanks. (edited)






