程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Introduction to PyScript.Run Python in your web browser

編輯:Python
  • 首頁
  • 軟件開發
  • Python

PyScript介紹.Run in your web browser Python

PyScriptAllows you to run directly in the browserPython腳本,與JavaScript並排,Two-way interaction between your code and the web page.

作者: Serdar Yegulalp

InfoWorldSenior Writer

dTosh / Shutterstock

目錄

  • 使用PyScript編程
  • 標准庫導入
  • 使用來自PyPI的庫
  • 本地導入
  • REPL標簽
  • 與JavaScriptEvent listener interaction

顯示更多

由Anaconda創建的PyScriptis an experimental but promising new technology,它使PythonThe runtime is supportingWebAssemblyis used as a scripting language in browsers.

Every modern browser in common use now supports itWebAssembly,This is in many languages(如C、C++和Rust)A high-speed runtime standard that can be compiled.Python的參考實現是用C語言編寫的,An early projectPyodide提供了Python運行時的WebAssembly移植.

[也在InfoWorld上:WebAssembly的崛起]

不過,PyScriptThe goal is to provide a complete browser environment,將PythonRuns as a web scripting language.它建立在Pyodide之上,But some functions are added or enhanced,Such as importing modules from the standard library、Use third-party imports、Configuration and Document Object Model(DOM)的雙向交互,As well as doing many others inPython和JavaScriptuseful things in the world.

現在,PyScriptStill a prototype and experimental project.Anaconda It is not recommended to use it in production.But curious users canPyScriptTry some examples on the website,And build experimental ones in the browser using the available componentsPython+JavaScript應用程序.

在這篇文章中,We will visitPyScript的基礎知識,See how it makesPython和JavaScript進行交互的.

使用PyScript編程

PyScriptThe core is a singleJavaScript include,You can add it to web pages.這個 include Basic loaded PyScript 運行時間,and the pair is automatically added PyScript Support for custom tags used in .

下面是一個PyScript的 "hello, world "Simple example of project.


<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/unstable/pyscript.js"></script>
</head>
<body>
<py-script output="out">
print("Hello world")
</py-script>
<div id="out"></div>
</body>
</html>
復制代碼

head 文檔中的script 標簽加載了PyScript的核心功能.pyscript.css Style sheets are optional,但很有用.在其他方面,It inserts a notification to the user about what the page is doing when the page loads--加載Python運行時,初始化,等等.

PythonThe code is included in the custom onepy-script 標簽中.請注意,The code should followPythonformatted with indentation conventions,否則將無法正常運行.If the editor you are using can reformat automaticallyHTML,請注意這一點;It might mess uppy-script 塊的內容,使其無法運行.

一旦PyScript組件加載完畢,任何PythonCode will be evaluated.If the script in the tag is writtenstdout (如print) 語句中,你可以通過提供一個output property to indicate where on the page to display the output.在這個例子中,腳本的stdout 被引導到ID為"out"div .

If you save it to a file,and open it in a web browser,You'll see one first "加載 "indicator and a pause,Because the browser gets itPyScriptrun time and set it up.The runtime should remain cached on future loads,But it still takes some time to activate.之後,Hello world should appear on the page.

標准庫導入

僅僅使用PythonScripts for built-in programs are only of little use.Python The standard library is in PyScript 中可用,Just like you're regular Python 中使用它一樣:只需import 並開始工作.The standard library is imported inPyScriptshould just work.

If you want to modify the above script block to display the current time,You don't need to use traditionalPython不同的方法.


import datetime
print ("Current date and time:", datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
復制代碼

使用來自PyPI的庫

如果我們想從PyPIinstall a package and use it?PyScript There is another tab,py-env ,It specifies the third-party packages that need to be installed.Let's replace the original script with these two blockspy-script 塊.


<py-env>
- humanize
</py-env>
<py-script output="out">
from datetime import datetime
import humanize
now_int = int(datetime.timestamp(datetime.now()))
now_fmt = humanize.intcomma(now_int)
print("It has been", now_fmt, "seconds since the epoch.")
</py-script>
復制代碼

py-env The block lets us list the packages to add,就像我們在 Python 項目的requirements.txt They are the same as listed in the file.Then we can treat like others Python Import and use them just like packages.在這個例子中,我們使用了一個名為humanize 的第三方軟件包,to make the digital output easier to read.

注意,Not all come fromPyPIpackages install and run as expected.例如,requests Requires access to network components that are not yet supported.(A possible workaround for this problem is to use pyodide.http.pyfetch ,它被原生支持).但是純 Python 包,如humanize ,should work fine.Anaconda Packages used in the provided examples,如numpy,pandas,bokeh, 或matplotlib ,也可以運行.

本地導入

For another common case,Suppose you want to download from other pages in the same directory tree as your web page Python 腳本中導入.Using import makes it easier to incorporate more Python The logic is moved out of the web page itself,There it mixes with your presentation,may become unwieldy.

通常,Python Use the other in the file system.py The existence of the file serves as an indication that it can be imported.PyScript doesn't work this way,So you need to specify which files are available as importable modules.

比方說,你有一個名為index.html 的網頁,在你的 web 服務器的某個目錄下,You want to put a name next to itmain.py 的 Python 文件.這樣,Your in-page script can be just thatimport main ,And you can put most of it Python The logic is limited to the actual.py 文件中.

在你的py-env Blocks specify what you want to import Python 文件.

- paths:`` - ./main.py

這將允許main.py ,in the same as the web page itself web 服務器目錄下,可以與import main 一起導入.

One important thing to remember.You can't do it on your browser本地The launched web page does such an import.這是由於WebAssemblyThis is due to restrictions on file system access both at runtime and by the browser itself.相反,You need to host these pages on a web server,to provide web pages and .py 文件.

[也在InfoWorld上:在2022年編寫現代Python的4個關鍵]

REPL 標簽

Python用戶應該熟悉Jupyter Notebook,它是Pythonin-browser real-time coding environment,Often used in mathematics and statistics.PyScriptA primitive building block is provided for such an environment,即py-repl 標簽.

py-repl Generate an input field on a web page,It functions like a very basic oneJupyter筆記本環境.下面是一個來自AnacondaDemonstrated example yourself.


<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<h1><b>pyscript REPL</b></h1>
Tip: press Shift-ENTER to evaluate a cell
<br>
<div>
<py-repl id="my-repl" auto-generate="true"> </py-repl>
</div>
</body>
</html>
復制代碼

運行這段代碼,You will see an input field,它的工作原理類似於Python的REPL.

目前,REPLLabels rarely have a documented way of customization.例如,If you want to programmatically access the contents of a cell or its result,There is no clear documentation on how to do this.

IDG

PyScript的類似Jupyter的REPLComponents allow you to run interactively within a pagePython,Although it's not very flexible or configurable yet.

與 JavaScript Event listener interaction

因為 PyScript 是基於pyodide 的,所以它使用pyodide mechanism to come with DOM 交互.例如,If we want to get the value of an input box on a web page and put it in our Python代碼中使用它,我們會這樣做.


<input id="txt">
<py-script>
from js import document, console
from pyodide import create_proxy
def _eventlog(e):
console.log(f"Input value: {e.target.value}")
eventlog = create_proxy(_eventlog)
document.getElementById("txt").addEventListener("input", eventlog)
</py-script>
復制代碼

js Libraries for many common ones JavaScript 實體提供了一個 Python 接口,比如documentconsole 對象.它們在PyScriptbehavior and presence inJavaScriptThe behavior is almost identical in .pyodide 中的create_proxy Functions allow us to take one Python function object and generate one for it JavaScript 接口,So it can be used as input event listener for the box.input Any keystrokes in the box will be logged to the console,But they can also be therePythonend is processed.

相關的.

  • Python
  • 網絡開發
  • 軟件開發

Serdar Yegulalp是InfoWorld的高級作家,專注於機器學習、容器化、devops、PythonEcosystem and regular reviews.

關注

Copyright 2022 IDG Communications, Inc.

如何選擇一個低代碼開發平台


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved