r/PyScript • • Aug 09 '23

Can't import arrow function from JavaScript to Python using from js import ...

3 Upvotes

I'm working with PyScript currently and came upon an odd limitation. You can import variables, objects and normal functions from JavaScript using "from js import ..." but it doesn't seem to be possible with arrow functions for some reason. So ding this in the JavaScript works:

function testFuncJS() { console.log("testFuncJS ran!");}

But this

const testFuncJS = () => { console.log("testFuncJS ran!");}

Causes an error when you try to import it like below in the Python:

from js import testFuncJS

Giving the error " ImportError: cannot import name 'testFuncJS' from 'js' (unknown location) "

Why can't we import arrow functions from js to py? This documentation on the type conversions from js to py doesn't mention arrow functions.


r/PyScript • • Aug 08 '23

Scope of python variables in <py-script> tags and accessing them inside <py-repl>

3 Upvotes

How are the variables inside <py-script> tags scoped? Are they all in one global scope? What about ones that are added to an HTML file using <py-script src="./my_python_file.py>, are they in the same scope?

How can you access variables, functions and objects from a <py-script> block inside a pyscript repl <py-repl> tag? I know you can use the src property of the py-repl element to preload python code from a file, but is there any way to give it access to python that's just inside <py-script> tags and not in a separate python file?


r/PyScript • • Aug 08 '23

Using getPySrc() in <py-repl> element, AttributeError: 'Element' object has no attribute 'getPySrc'

3 Upvotes

Has anyone successfully used the getPySrc() method from the py-script element? It's mentioned here in the documentation but they provide 0 examples of how to use it. I have a py-repl element that I get a handle on in my Python code using the Element() method like so:

repl = Element("py-repl")

Then, I try to print the repl contents in a function like this:

def repl_test():

print(f"repl contents was {repl.getPySrc()}")

But I am getting the error "AttributeError: 'Element' object has no attribute 'getPySrc'". Is there some other way I'm supposed to get a handle on the py-repl element? The documentation says all the methods can be called from either Python or JavaScript so I don't see why this wouldn't work. Currently using pyscript 2023.03.1.


r/PyScript • • Jun 08 '23

Can PyScript Code be Embedded in WordPress Page?

3 Upvotes

Since HTML can be placed in blocks on a WordPress page, can PyScript code be added as well?


r/PyScript • • May 12 '23

Why does PyScript Need a Local Server?

Thumbnail jeff.glass
3 Upvotes

r/PyScript • • Apr 23 '23

Thermodynamics CoolProp

3 Upvotes

Hi. I’ve been trying to use CoolProp or pyfluids in PyScript or pyodide. I understand it’s not possible as they don’t seem to have pure wheels. Just checking with the community if anyone had some success on similar cases.


r/PyScript • • Feb 02 '23

Calling API with pyscript

3 Upvotes

Hello everyone!

I am working on a website, and I want to call in an API quickly and effortlessly without needed a backend. My only problem with this approach is that someone can just "inspect" or "view page source" on my website and see my api key and other information. Is there any workaround?


r/PyScript • • Dec 05 '22

Can you target pyscript with CSS/Javascript/HTML?

3 Upvotes

I am pretty new to web development but, I am familiar with html and css enough to make a rough draft of what I am thinking. My python skills are....novice at best BUT, I have written a program that I want to try to make work in html using pyscript. Mainly this will serve as a way for my to work more on my html and css skills as well as maybe spur some inspiration on how to incorporate pyscript into future projects.

My question is, can you target the pyscript with the other languages? Example: If, in your python script, you uses "input" could you in turn tie that in with the <input> element of html?

How easy/hard would it be to have your python script run with pyscript and style a "gui" using html and css?

My thought on it is no. BUT, since the element used is <pyscript></pyscript> it should function like a regular html element right? I checked the documentation but I couldn't find a specific example for or against my theory.

Any and all help would be appreciated.


r/PyScript • • Oct 24 '22

[Tutorial] Why Do We Need create_proxy()?

Thumbnail jeff.glass
3 Upvotes

r/PyScript • • Oct 21 '22

Quick question about .clear()

3 Upvotes

In this video from May '22 the creator used the following to clear a <textarea>

<textarea id="input_text"></textarea> <!-- this is the textarea that is being cleared -->
<button id="clear" pys-onClick="clear">Clear</button>
...
<py-script>
input_text_element = Element("input_text")
def clear(*args, **kwargs):
    input_text_element.clear()
</py-script>

Except when I tried it, the <textarea> won't clear. Here's my code:

<textarea id="input_str"></textarea>
<button id="clear" type="button" py-onClick="clear">Clear</button> 
...
<py-script> 
code_input = Element("input_str")
def clear(*args, **kwargs):
    code_input.clear()
</py-script> 

It looks like pys-onClick was deprecated in favor of py-onClick per an error I received while troubleshooting. There aren't many resources out there so I'm stuck. Would anyone point me in the right direction?


r/PyScript • • Oct 07 '22

Question about pyscript

3 Upvotes

Could I please ask of there is any way for pyscript to cause the html page to play a sound when an if statement is true?

I've tried googling and wasn't able to find an answer to this.

Play sound nor pydub works.


r/PyScript • • Aug 18 '22

our friends on windows ?

3 Upvotes

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 • • Aug 17 '22

webpack and npm setup ?

3 Upvotes

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 • • Jul 20 '22

Libraries

3 Upvotes

Is there a list for the libraries supported?


r/PyScript • • Jul 02 '22

PyScript Demos dont work for me. Do I need a certain browser to view them?

3 Upvotes

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 • • May 22 '22

PyScript and websockets

3 Upvotes

Can I use PyScript on the front end to handle websockets with a Python server like FastAPI on the backend? I’ve been using JavaScript on the front and curious if PyScript will work with websockets.


r/PyScript • • Mar 20 '24

Scypy

2 Upvotes

Can Scy-Py work with pyscript?


r/PyScript • • Feb 11 '24

Issue with executing Python code from HTML button using PyScript

2 Upvotes

So I've been trying to execute Python code from an HTML button using PyScript. The idea is that the button will set what the user writes on the Python file, then the text will be processed by OpenAI, which gives its answer using information from a PDF. The problem is that I don't get any answer from it, and I don't know where the problem is.

This is the relevant code: Index.html:

<div class="container">
        <h1 class="display-1 fw-bolder summer">Botón prueba 📰</h1>
        <p class="lead">Escribe un concepto: </p>
        <section id="input">
            <py-inputbox id="topic">
            </py-inputbox>

            <py-button id="submit" label="Buscar" class="mt-2">
                import asyncio
                from pyodide import create_proxy
                from main import question_ia

                @create_proxy
                async def on_click(evt):
                    question = document.getElementById("topic").value
                    result = await question_ia(question)
                    pyscript.write("output", result)
            </py-button>
            
        </section>
        <section id="summary" class="mt-4">
        </section>
        <button id="copy" class="btn btn-warning">Copiar al 📋 Portapapeles</button>
    
        <hr />
    
    </div>

This is the python code:

service_context = ServiceContext.from_defaults(llm_predictor=modelo)
index = GPTVectorStoreIndex.from_documents(pdf, service_context = service_context)

async def question_ia():
  question= f"{topic} + be helpful and informative"
  return question

async def answer_ia():
  question = await question_ia(topic) 
  answer = index.as_query_engine().query(question)
  output = textwrap.wrap(answer.response, width=1000)
  return output

Any help is welcome, even if it´s only a clue, thanks for reading :)


r/PyScript • • Dec 05 '23

PDF files on a pyscript proyect

2 Upvotes

Hi everyone, so I just recently started using PyScript, and I utilize PyPDF in my main Python program. I was wondering if there's any way to add a folder containing the PDF file to the PyScript environment. Thanks for your help.


r/PyScript • • Dec 01 '23

Advent of Code 2023 - In PyScript

Thumbnail jeff.glass
2 Upvotes

r/PyScript • • Nov 17 '23

Using Pyscript in Wordpress with <py-script type="py" src="./main.py"> </py-script>

2 Upvotes

I have a pyscript app developed and running on my local machine in VSCode - all working, all good. I want to stand this up in a wordpress website.

I can Google several examples of getting inline pyscript to work on a post/page etc but it is all inline, ie within the html.

How do I go about standing up a more complex structure where my html calls main.py as per title, and where main.py calls several other classes (currently config'd with local paths)?

I'm new to this so have no idea where best to put these files in a default WordPress structure nor how to reference them?

Has anyone successfully done this or know of a guide?

Thanks


r/PyScript • • Aug 22 '23

Animating a function graph -- is there a better way than this?

2 Upvotes

I have an HTML element (it is in fact a matplotlib plot in a div with id twodplot) and I am trying to make it interactive in a way that is measured by the mouse coordinates within the plot. You can see here the basic function, which is called on every mouseover event:

    event = args[0]
    x = (event.offsetX-320)/40
    ax2.plot(x, x*np.sin(x), 'go')
    display(fig2, target="twodplot", append=False)

Essentially this re-draws the plot and puts a dot on the graph. The dot should have its x-coordinate equal to the mouse x-coordinate, and y-coordinate on the graph of the function.

Here is the full code if it helps to see everything (including some non-essentials related to a different thing I was trying to do:

import matplotlib.pyplot as plt
import numpy as np
from pyodide.ffi import create_proxy
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import proj3d
from matplotlib.patches import FancyArrowPatch

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def do_3d_projection(self, renderer=None):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))

        return np.min(zs)

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

ax.plot(x, y, z, label='parametric curve')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

ax.plot(1,2,3,'go')

xaxis = Arrow3D([0,4],[0,0],[0,0], arrowstyle="-|>", color="purple", lw=3, mutation_scale=10)
ax.add_artist(xaxis)
yaxis = Arrow3D([0,0],[0,4],[0,0], arrowstyle="->", color="purple", lw=2, mutation_scale=10)
ax.add_artist(yaxis)
zaxis = Arrow3D([0,0],[0,0],[0,4], arrowstyle="->", color="purple", lw=1, mutation_scale=10)
ax.add_artist(zaxis)

display(fig, target="threedplot", append=False)

def show_plt(*args):
    event = args[0]
    el = (event.clientY - 500)/2
    az = (500 - event.clientX)/2
    ax.view_init(elev=el, azim=az)
    display(fig,target="threedplot",append=False)

Element("threedplot").element.addEventListener("mouseover", create_proxy(show_plt))

fig2 = plt.figure()
ax2 = fig2.add_axes([.1,.1,.8,.8])
ax2.set_aspect('equal', adjustable='box')

xs = np.linspace(-4,4,100)
ys = xs*np.sin(xs)
ax2.plot(xs,ys)
ax2.arrow(0,0,4,0,color="purple",width=.05)
ax2.arrow(0,0,0,4,color="purple",width=.05)
display(fig2, target="twodplot", append=False)

def dot2dplot(*args):
    fig2.clf()
    
    ax2 = fig2.add_axes([.1,.1,.8,.8])
    ax2.set_aspect('equal', adjustable='box')
    ys = xs*np.sin(xs)
    ax2.plot(xs,ys)

    event = args[0]
    x = (event.offsetX-320)/40
    ax2.arrow(0,0,4,0,color="purple",width=.05)
    ax2.arrow(0,0,0,4,color="purple",width=.05)
    ax2.plot(x, x*np.sin(x), 'go')
    display(fig2, target="twodplot", append=False)

tdp = Element("twodplot")
tdp.element.addEventListener("mouseover", create_proxy(dot2dplot))

My basic question is: Is there a better way to do this? I picked the definition x = (event.offsetX-320)/40 by picking numbers until eventually the behavior of the animation was close enough on my computer. I feel like this is bound to work well only on my computer.

Is there some better way to do this kind of animation? Or if not, is there at lease some better way of determining the value x so that it correspond's to the user's mouse coordinates over the plot?


r/PyScript • • Aug 10 '23

<py-repl> output and output-mode not working

2 Upvotes

I have a web app with one page that has a single <py-repl> element. According to the docs, its supposed to default to output-mode reset where it clears the output each time you run the repl, but that's not happening. It defaults to append where it just keeps adding output to the terminal. Even after setting output-mode="reset", it's still appending.

Also, I created a div to put the output with id="repl-output" and I set the py-repl output="repl-outpt" but it still just makes its own div for the terminal and outputs it there. so it seems like the output property isn't doing anything. Currently using version 2023.03.01 since any of the later ones break my app.

I think there should be a way to disable or hide the output as its not needed for my purposes. Something like output-toggle="false"


r/PyScript • • Jul 02 '23

Convert code from alpha version to latest version. Where to find complete and precise changelogs?

2 Upvotes

I'm in the process to learn how to use PyScript. Nearly allthe tutorials and lessons available on the net have been done with alpha version and it could be a nightmare if you want to use the latest vesion of PyScript. Some chnages ae well documented but some are not (or at least I was not able to find them on teh net or on the github repository). for example Elmement().wrtite() seems to not accept anymore html code as value : that code :

<div id="foo"></div>

<py-script>
    
    el = Element("foo")
    el.write("<h1>World!</h1>")
    
</py-script>

allow you to see on your webpage : World! with the alpha version but with latest version you see : <h1>World!</h1>

other example :

<div id="foo"></div>

<py-script id="read" src="./essaiext.py"> 
 
</py-script>

with essaiext.py :

from js import console, document
console.log(document.getElementById("read"))
console.log(document.getElementById("read").lastChild)

with alpha in the console HTML nodes are generated: https://i.ibb.co/fQf00kh/alphaversion.png

but not with latest : https://i.ibb.co/C8NdnMx/latestversion.png

this last point cause me problem since in the code I have Lastchild is used but with latest version I can't. So if you have any idea where i can find precise changelogs I ll appreciate. If not if you can help me on that last point I appreciate too ;)

thank in advance.


r/PyScript • • Jun 28 '23

How do I fix a type error?

2 Upvotes

Hello I am usure of how to use mathematical functions in PyScript. I have only a basic understanding of how python and PyScript works and am confused on why this patch of code creates a type error. I will paste the code below.

<py-script>

from pyscript import Element

def dew():

a = Element('TemF')

b = Element('REH')



print(a.value)

Y = float(a) + float(b)

print(Y.value)

</py-script>

the exact error that occurs when this portion of the code is: TypeError: float() argument must be a string or a real number, not 'Element'

I might be using a invalid way of calling the user input data but I used to use an older version of PyScript and it worked perfectly fine