Skip to content
Advertisement

How do I use pyscript in my HTML code and return output

I am trying to call my python function created. But not getting any output and no resource how to achieve.

Code :

JavaScript

It would be great helpful if some one provide input like …

How to pass selected file to my function and python will be executed & return output on screen.

Advertisement

Answer

When writing Python in the browser, you must rethink how actions are performed. Typically, Python programs are procedural. Browser-based applications are asynchronous.

The first step is to enable asynchronous features:

JavaScript

Browser based programs cannot directly access the local file system. Your code is not doing what you think it is.

JavaScript

Your code is reading from the browser virtual file system which is allowed. You are trying to process the event from the ` element but trying to access a different location.

Note: I do not know what the file contents of “filename” are, so I did not incorporate your code after the file is read.

Your code cannot read files. You must ask the browser to read a file for your application. This is performed with the FileReader class.

Example:

JavaScript

Another problem is that you are passing a Python function as a callback. That will not work. Instead, you must call create_proxy() to create a callback proxy for the Python function. The browser will call the proxy which then calls your Python function.

Example:

JavaScript

I put a copy of this solution on my website. You can right-click on the page to download the source code.

File Example Demo

Complete solution:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement