PyScript All In One
PyScript All In One
Run Python in Your HTML
https://github.com/pyscript/pyscript
docs & examples
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<h1>PyScript demo</h1>
</head>
<body>
<pre>
<py-script>
print('Hello, World!')
</py-script>
<py-script>
# python 注释
from datetime import datetime
now = datetime.now()
# display 输出
display(now.strftime("%m/%d/%Y, %H:%M:%S"))
# print 注释,自带背景
print(now.strftime("%m/%d/%Y, %H:%M:%S"))
</py-script>
</pre>
<py-script>
print('Hello, World!')
</py-script>
<py-script>
# python 注释
from datetime import datetime
now = datetime.now()
# display 输出
display(now.strftime("%m/%d/%Y, %H:%M:%S"))
# print 注释,自带背景
print(now.strftime("%m/%d/%Y, %H:%M:%S"))
</py-script>
</body>
</html>
https://pyscript.net/examples/hello_world.html
<py-register-widget src="./pylist.py" name="py-list" klass="PyList"></py-register-widget>
<py-config>
[[fetch]]
files = ["./utils.py"]
</py-config>
<py-script>
from js import document
from pyodide.ffi.wrappers import add_event_listener
def add_task(*ags, **kws):
# create a new dictionary representing the new task
new_task_content = Element("new-task-content")
task = { "content": new_task_content.value, "done": False, "created_at": dt.now() }
# add a new task to the list and tell it to use the `content` key to show in the UI
# and to use the key `done` to sync the task status with a checkbox element in the UI
myList.add(task)
# clear the inputbox element used to create the new task
new_task_content.clear()
def on_click(evt):
add_task()
def handle_keypress(evt):
if evt.key == "Enter":
add_task()
add_event_listener(
document.getElementById("new-task-content"),
"keypress",
handle_keypress
)
</py-script>
<div class="py-box">
<input id="new-task-content" />
<button py-click="add_task()" id="new-task-btn" class="py-button">Add Task!</button>
</div>
<py-list id="myList"></py-list>
<py-repl id="my-repl" auto-generate="true"> </py-repl>
# pylist.py
import pyscript
from datetime import datetime as dt
class PyItem(pyscript.PyItemTemplate):
def on_click(self, evt=None):
self.data["done"] = not self.data["done"]
self.strike(self.data["done"])
self.select("input").element.checked = self.data["done"]
class PyList(pyscript.PyListTemplate):
item_class = PyItem
def add(self, item):
if isinstance(item, str):
item = {"content": item, "done": False, "created_at": dt.now()}
super().add(item, labels=["content"], state_key="done")
https://pyscript.net/examples/todo-pylist.html
<py-config>
[[fetch]]
files = ["./antigravity.py"]
</py-config>
<div>
<py-repl id="my-repl" auto-generate="true"> </py-repl>
</div>
# antigravity.py
import random
import sys
from js import DOMParser, document, setInterval
from pyodide.ffi import create_proxy
from pyodide.http import open_url
class Antigravity:
url = "./antigravity.svg"
def __init__(self, target=None, interval=10, append=True, fly=False):
target = target or sys.stdout._out
self.target = (
document.getElementById(target) if isinstance(target, str) else target
)
doc = DOMParser.new().parseFromString(
open_url(self.url).read(), "image/svg+xml"
)
self.node = doc.documentElement
if append:
self.target.append(self.node)
else:
self.target.replaceChildren(self.node)
self.xoffset, self.yoffset = 0, 0
self.interval = interval
if fly:
self.fly()
def fly(self):
setInterval(create_proxy(self.move), self.interval)
def move(self):
char = self.node.getElementsByTagName("g")[1]
char.setAttribute("transform", f"translate({self.xoffset}, {-self.yoffset})")
self.xoffset += random.normalvariate(0, 1) / 20
if self.yoffset < 50:
self.yoffset += 0.1
else:
self.yoffset += random.normalvariate(0, 1) / 20
_auto = Antigravity(append=True)
fly = _auto.fly
https://pyscript.net/examples/repl.html
demos
python crawler
__author__ = 'xray'
# coding: utf8
from wiki_baike import url_manager, html_downloader, html_parser, html_outputer
import logging
class SpiderMain(object):
def __init__(self):
self.url = url_manager.UrlManager()
self.downloader = html_downloader.HtmlDownloader()
self.parser = html_parser.HtmlParser()
self.outputer = html_outputer.HtmlOutputer()
def craw(self, root_url):
count = 1
self.urls.add_new_url(root_url)
while self.urls.has_new_url():
try:
new_url = self.urls.get_new_url()
print 'craw %d : %s' % (count, new_url)
html_cont = self.downloader.download(new_url)
new_urls, new_data = self.parser.parse(new_url, html_cont)
self.urls.add_new_urls(new_urls)
self.outputer.collect_data(new_data)
if count == 1000:
break
count += 1
except Exception as e:
logging.exception(e)
print 'error'
self.outputer.output_html()
if __name__=='__main__':
root_url = 'http://baike.baidu.com/view/21087.html'
# root_url = 'https://rollbar.com/docs/'
obj_spider = SpiderMain()
obj_spider.craw(root_url)
refs
https://realpython.com/pyscript-python-in-browser/
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16513674.html
未经授权禁止转载,违者必究!