Html скрипт на питоне

Html скрипт на питоне

The element, also available as , lets you execute multi-line Python scripts both inline and via a src attribute.

Attributes#

You don’t need to add long python code in py-script, you can provide url of the python source file in the py-script tag with the src attribute. When a Python file is referred with the src attribute it is executed, and then added to the namespace where it was referred.

The id of a DOM element to route sys.stdout and stderr to, in addition to sending it to the

The id of a DOM element to route just sys.stderr to, in addition to sending it to the

output#

If the output attribute is provided, any output to sys.stdout or sys.stderr is written to the DOM element with the ID matching the attribute. If no DOM element is found with a matching ID, a warning is shown. The msg is output to the innerHTML of the HTML Element, with newlines ( \n’ ) converted to breaks (
).

This output is in addition to the output being written to the developer console and the if it is being used.

stderr#

If the stderr attribute is provided, any output to sys.stderr is written to the DOM element with the ID matching the attribute. If no DOM element is found with a matching ID, a warning is shown. The msg is output to the innerHTML of the HTML Element, with newlines ( \n’ ) converted to breaks (
).

This output is in addition to the output being written to the developer console and the if it is being used.

Examples#

Inline element#

Let’s execute this multi-line Python script to compute π and print it back onto the page

html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-script> print("Let's compute π:") def compute_pi(n): pi = 2 for i in range(1,n): pi *= 4 * i ** 2 / (4 * i ** 2 - 1) return pi pi = compute_pi(100000) s = f"π is approximately " print(s) py-script> body> html> 

Using element with src attribute#

we can also move our python code to its own file and reference it via the src attribute.

# compute_pi.py print("Let's compute π:") def compute_pi(n): pi = 2 for i in range(1,n): pi *= 4 * i ** 2 / (4 * i ** 2 - 1) return pi pi = compute_pi(100000) s = f"π is approximately pi:.3f>" print(s) 

Since both compute_pi.py and index.html are in the same directory, we can reference the python file with a relative path.

html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-script src="compute_pi.py">py-script> body> html> 

Writing into labeled elements#

In the example above, we had a single tag printing one or more lines onto the page in order. Within the , you can use the Element class to create a python object for interacting with page elements. Objects created from the Element class provide the .write() method which enables you to send strings into the page elements referenced by those objects.

For example, we’ll add some style elements and provide placeholders for the tag to write to.

html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"> head> body> b>p>Today is u>label id='today'>label>u>p>b> br> div id="pi" class="alert alert-primary">div> py-script> import datetime as dt Element('today').write(dt.date.today().strftime('%A %B %d, %Y')) def compute_pi(n): pi = 2 for i in range(1,n): pi *= 4 * i ** 2 / (4 * i ** 2 - 1) return pi pi = compute_pi(100000) Element('pi').write(f'π is approximately ') py-script> body> html> 

Источник

Getting started with PyScript#

This page will guide you through getting started with PyScript.

Development setup#

PyScript does not require any development environment other than a web browser (we recommend using Chrome) and a text editor, even though using your IDE of choice might be convenient.

If you’re using VSCode, the Live Server extension can be used to reload the page as you edit the HTML file.

Installation#

There is no installation required. In this document, we’ll use the PyScript assets served on https://pyscript.net.

If you want to download the source and build it yourself, follow the instructions in the README.md file.

Your first PyScript HTML file#

Here’s a “Hello, world!” example using PyScript.

Using your favorite editor, create a new file called hello.html in the same directory as your PyScript, JavaScript, and CSS files with the following content, and open the file in your web browser. You can typically open an HTML by double-clicking it in your file explorer.

html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-script> print('Hello, World!') py-script> body> html> 

Using a Local Server#

In some situations, your browser may forbid loading remote resources like pyscript.js and pyscript.css when you open an HTML file directly. When this is the case, you may see your Python code in the text of the webpage, and the browser developer console may show an error like “Cross origin requests are only supported for HTTP.” The fix for this is to use a simple local server to make your html file available to the browser.

If you have python installed on your system, you can use it’s basic built-in server for this purpose via the command line. Change the current working directory of your terminal or command line to the folder where your HTML file is stored. From this folder, run python -m http.server 8080 —bind 127.0.0.1 in your terminal or command line. With the server program running, point your browser to http://localhost:8080 to view the contents of that folder. (If a file in that folder is called index.html , it will be displayed by default.)

A more complex example#

Now that we know how you can create a simple ‘Hello, World!’ example, let’s see a more complex example. This example will use the Demo created by Cheuk Ting Ho. In this example, we will use more features from PyScript.

Setting up the base index file#

Let’s create a new file called index.html and add the following content:

html> head> title>Ice Cream Pickertitle> meta charset="utf-8"> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> body> html> 

In this first step, we have created the index file, imported pyscript.css and pyscript.js . We are ready to start adding the elements we need for our application.

Importing the needed libraries#

For this example, we will need to install pandas and matplotlib . We can install libraries using the tag so we can import them later. Please refer to the documentation for more information.

html> head> title>Ice Cream Pickertitle> meta charset="utf-8"> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-config> packages = ["matplotlib", "pandas"] py-config> body> html> 

Importing the data and exploring#

Now that we have installed the needed libraries, we can import and explore the data. In this step, we need to create a tag to import our dependencies, read the data with pandas and then use py-repl to explore the data.

html> head> title>Ice Cream Pickertitle> meta charset="utf-8"> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-config> packages = ["matplotlib", "pandas"] py-config> py-script> import pandas as pd from pyodide.http import open_url url = ( "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv" ) ice_data = pd.read_csv(open_url(url)) py-script> py-repl> ice_data py-repl> body> html> 

Note that we are adding ice_data to py-repl to pre-populate the REPL with this variable, so you don’t have to type it yourself.

Creating the plot#

Now that we have the data, we can create the plot. We will use the matplotlib library to make the plot. We will use the display API to display the plot on the page. You may want to read the display documentation for more information.

html> head> title>Ice Cream Pickertitle> meta charset="utf-8"> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-config> packages = ["matplotlib", "pandas"] py-config> py-script> import pandas as pd import matplotlib.pyplot as plt from pyodide.http import open_url url = ( "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv" ) ice_data = pd.read_csv(open_url(url)) def plot(data): plt.rcParams["figure.figsize"] = (22,20) fig, ax = plt.subplots() bars = ax.barh(data["name"], data["rating"], height=0.7) ax.bar_label(bars) plt.title("Rating of ice cream flavours of your choice") display(fig, target="graph-area", append=False) plot(ice_data) py-script> py-repl> ice_data py-repl> div id="graph-area">div> body> html> 

Select specific flavours#

Now that we have a way to explore the data using py-repl and a way to create the plot using all of the data, it’s time for us to add a way to select specific flavours.

html> head> title>Ice Cream Pickertitle> meta charset="utf-8"> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-config> packages = ["matplotlib", "pandas"] py-config> py-script> import js import pandas as pd import matplotlib.pyplot as plt from pyodide.http import open_url from pyodide.ffi import create_proxy url = ( "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv" ) ice_data = pd.read_csv(open_url(url)) current_selected = [] flavour_elements = js.document.getElementsByName("flavour") def plot(data): plt.rcParams["figure.figsize"] = (22,20) fig, ax = plt.subplots() bars = ax.barh(data["name"], data["rating"], height=0.7) ax.bar_label(bars) plt.title("Rating of ice cream flavours of your choice") display(fig, target="graph-area", append=False) def select_flavour(event): for ele in flavour_elements: if ele.checked: current_selected = ele.value break if current_selected == "ALL": plot(ice_data) else: filter = ice_data.apply(lambda x: ele.value in x["ingredients"], axis=1) plot(ice_data[filter]) ele_proxy = create_proxy(select_flavour) for ele in flavour_elements: if ele.value == "ALL": ele.checked = True current_selected = ele.value ele.addEventListener("change", ele_proxy) plot(ice_data) py-script> div id="input" style="margin: 20px;"> Select your 🍨 flavour: br/> input type="radio" id="all" name="flavour" value="ALL"> label for="all"> All 🍧label> input type="radio" id="chocolate" name="flavour" value="COCOA"> label for="chocolate"> Chocolate 🍫label> input type="radio" id="cherry" name="flavour" value="CHERRIES"> label for="cherry"> Cherries 🍒label> input type="radio" id="berries" name="flavour" value="BERRY"> label for="berries"> Berries 🍓label> input type="radio" id="cheese" name="flavour" value="CHEESE"> label for="cheese"> Cheese 🧀label> input type="radio" id="peanut" name="flavour" value="PEANUT"> label for="peanut"> Peanut 🥜label> div> py-repl> ice_data py-repl> div id="graph-area">div> body> html> 

Источник

Say Hello to PyScript

PyScript is a framework that allows users to create rich Python applications in the browser using HTML’s interface and the power of Pyodide, WASM, and modern web technologies. The PyScript framework provides users at every experience level with access to an expressive, easy-to-learn programming language with countless applications.

What is PyScript? Well, here are some of the core components:

  • Python in the browser: Enable drop-in content, external file hosting, and application hosting without the reliance on server-side configuration
  • Python ecosystem: Run many popular packages of Python and the scientific stack (such as numpy, pandas, scikit-learn, and more)
  • Python with JavaScript: Bi-directional communication between Python and Javascript objects and namespaces
  • Environment management: Allow users to define what packages and files to include for the page code to run
  • Visual application development: Use readily available curated UI components, such as buttons, containers, text boxes, and more
  • Flexible framework: A flexible framework that can be leveraged to create and share new pluggable and extensible components directly in Python

All that to say… PyScript is just HTML, only a bit (okay, maybe a lot) more powerful, thanks to the rich and accessible ecosystem of Python libraries.

In short, our mission is to bring programming for the 99%.

Источник

Читайте также:  How to remove index php
Оцените статью