Search
Duplicate
moon
sun

PyScript기초

first_Test.git
roughkyo
목차(클릭하세요)
💡
파이스크립의 실행을 위한 2가지 방법 1. 깃허브 레포지토리를 이용한 웹호스팅(page 추가) 2. codepen을 사용해서 바로 확인

0.공식문서

•
파이 스크립트 공식문서

1. PyScript란?

1.
HTML 인터페이스와 Pyodide, WASM 및 최신 웹 기술을 사용하여 웹 브라우저에서 동작하는 다양한 Python 애플리케이션을 만들 수 있는 프레임워크
2.
Python을 이용해 웹 브라우저에서 동작하는 완성도 높은 애플리케이션을 만들 수 있도록, 여러 공개된 기술을 프레임워크와 결합하는 것을 목표로 하는 메타 프로젝트

2. 사용법(기초)

1.
PyScript를 사용하려면 적절한 PyScript 파일들을 HTML 파일의 head 태그에 아래와 같이 추가해야 함
2.
현재 PyScript가 구현하는 요소들
•
<py-script>: 웹 페이지 내에서 실행 가능한 Python 코드를 정의하는 데 사용됨. 요소 자체는 페이지에 렌더링되지 않으며 논리를 추가하는 데만 사용됨
•
<py-repl>: 웹 페이지에 코드 편집기로 렌더링됨. 사용자가 실행 코드를 작성할 수 있도록 하는 REPL 구성 요소를 생성함.
<head> <title>파이스크립트로 간단한 파이썬 코드 실행해보기</title> <meta charset="UTF-8"> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <!-- 바디(body) 영역안에 파이스크립트 영역을 만들어주고 필요한 코드 적어주기 --> <py-script> print('hello, world!') </py-script> </body> </html>
JavaScript
복사
3. 기초 코드 실행결과
4.
연산 결과 실행해보기
<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("π 연산 결과:") 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) print(f"π 연산 결과는 {pi:.3f} 입니다.") </py-script> </body> </html>
JavaScript
복사

3. 사용법(응용)

3.1. 레이블이 지정된 요소에 쓰기

•
1. 페이지의 레이블이 지정된 요소에 문자열을 보내는 pyscript의 .write() 메서드를 사용
•
2. datetime을 이용해 만든 날짜 값은 id가 ‘today’인 태그로 보내고, 위에서 만든 pi 연산 결과값은 id가 ‘pi’인 태그로 보내는 스크립트
```javascript <html> <head> <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> </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 pyscript.write('today', 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) pyscript.write('pi', f"π 연산 결과는 {pi:.3f} 입니다.") </py-script> </body> </html> ```
Markdown
복사

3.2. py-config 태그 사용하기

1.
py-config 태그를 사용하여 PyScript 애플리케이션에 대한 종속성 선언과 함께 일반적인 메타 데이터를 설정할 수 있음 - 설정은 TOML 혹은 JSON 형식으로 작성해야 함 - 여기서는 JSON 형식에 대해서만 살펴보기로 함 - py-config 태그는 보통 head 태그 안에 작성
2.인라인으로 설정하는 방법 ```javascript <head> <py-config type="json"> { "autoclose_loader": true, "runtimes": [{ "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", "name": "pyodide-0.21.2", "lang": "python" }] } </py-config> </head> ```
Markdown
복사
3. src 속성을 이용해 설정하는 방법 - 1. html안에서 ```javascript <head> <py-config type="json" src="./custom.json"></py-config> </head> ``` - 2. 별도 json으로 css 셋팅 ```json { "autoclose_loader": true, "runtimes": [{ "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", "name": "pyodide-0.21.2", "lang": "python" }] } ``` 4. 인라인+ src속성을 모두 사용하는 방법 - 설정을 태그 안에도 작성하고, src 속성에도 동시에 작성할수도 있음 ```javascript <head> <py-config type="json" src="./custom.json"> { "paths": ["./utils.py"] } </py-config> </head> ```
JavaScript
복사

3.3. NumPy, Matplotlib 패키지 사용하기

1. PyScript에서 NumPy와 Matplotlib 패키지를 지원하고 있음 - 예) ```<py-script output="plot">``` 처럼 사용 - 실행시 스크립트의 마지막 줄에 있는 표현식을 가져와서 pyscript.write('plot', fig)를 실행하는 역할 2. 주의점 - 변경된 파이스크립트에 따르면, numpy 와 matplotlib 등과 같은 라이브러리를 사용하려면 패키징(packing)과 import 를 해주어야 함 - 그 방법이 이전과 달리 먼저 HTML 태그에서 <py-config> 태그를 이용해 2개의 라이브러리를 패키징해주어야 함 - 파이썬과 다르게 그래프를 출력할 대상을 특정할 수 있다는 점이 특이함 - 이를테면 HTML 태그로 아래와 같이 그래프를 그릴 대상을 정의하고 - ```<div id="graph"></div>``` - 파이스크립트에서 결과를 출력할 때는 print 대신 display 명령을 사용하는 것 - 이 때 target 에 대상의 id값을 명시해야 함 - ``` display(plt, target="graph")``` 3. 실습 - plot.html을 작성 ```javascript <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>라이브러리 사용</title> <!-- linking to PyScript assets --> <link rel="stylesheet" href="https://pyscript.net/releases/2022.12.1/pyscript.css" /> <script defer src="https://pyscript.net/releases/2022.12.1/pyscript.js"></script> </head> <body> <!-- display 명령에서 출력할 div --> <div id="graph"></div> <!-- 설치할 서드파티 --> <py-config> packages = ["numpy", "matplotlib"] </py-config> <py-script> import numpy as np import matplotlib.pyplot as plt arr = np.array([5, 3, 4, 1, 2]) plt.plot(arr) plt display(plt, target="graph") </py-script> </body> </html> ```
Markdown
복사

3.3.1. 기본형 plot

```javascript <html> <head> <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <py-config type="json"> { "packages": ["numpy", "matplotlib"] } </py-config> </head> <body> <h1>Let's plot random numbers</h1> <div id="plot"></div> <py-script output="plot"> import matplotlib.pyplot as plt import numpy as np x = np.random.randn(1000) y = np.random.randn(1000) fig, ax = plt.subplots() ax.scatter(x, y) fig </py-script> </body> </html> ```
Markdown
복사

3.3.2. 함수형 plot

```javascript <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>라이브러리 사용</title> <!-- linking to PyScript assets --> <link rel="stylesheet" href="https://pyscript.net/releases/2022.12.1/pyscript.css" /> <script defer src="https://pyscript.net/releases/2022.12.1/pyscript.js"></script> </head> <body> <body> <py-config> packages = ["numpy", "matplotlib"] </py-config> <h1>Let's plot random numbers</h1> <div id="plot"></div> <py-script> import matplotlib.pyplot as plt import numpy as np # Plot 생성 함수 def create_plot(): x = np.random.randn(1000) y = np.random.randn(1000) plt.scatter(x, y) plt display(plt, target="plot") # 초기 plot 생성 create_plot() </py-script> </body> </html> ```
Markdown
복사

3.3.3. 버튼를 활용한 선택형 plot

1. 버튼을 생성 2. 목록에서 차트를 선택할 수 있도록 3. csv데이터는 외부url참조 하도록
```javascript <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="chrome,safari"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> <py-env> - matplotlib - pandas - seaborn </py-env> <title>Py-Script test</title> </head> <body> <div class="row"> <div class="col-sm-2 p-2 ml-4 mb-1"> <button type="button" class="btn btn-secondary">Select chart from list:</button> </div> <div class="col-sm-4 p-2 mr-4 mb-1"> <select class="form-control" id="select"> <option value="Tmax">최대온도</option> <option value="Tmin">최저온도</option> <option value="Sun">맑은날</option> <option value="Rain">비오는날</option> </select> </div> <div class="row"> <div class="col-sm-6 p-2 shadow ml-4 mr-4 mb-4 bg-white rounded"> <div id="chart1"></div> </div> </div> <py-script> # Import libraries import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Get the data from pyodide.http import open_url url = 'https://raw.githubusercontent.com/alanjones2/uk-historical-weather/main/data/Heathrow.csv' url_content = open_url(url) df = pd.read_csv(url_content) # filter the data for the year 2020 df = df[df['Year']==2020] # Function to plot the chart def plot(chart): fig, ax = plt.subplots() sns.lineplot(y=chart, x="Month", data=df, ax=ax) pyscript.write("chart1",fig) # Set up a proxy to be called when a 'change' # event occurs in the select control from js import document from pyodide import create_proxy # Read the value of the select control # and call 'plot' def selectChange(event): choice = document.getElementById("select").value plot(choice) # set the proxy def setup(): # Create a JsProxy for the callback function change_proxy = create_proxy(selectChange) e = document.getElementById("select") e.addEventListener("change", change_proxy) setup() # Intitially call plot with 'Tmax' plot('Tmax') </py-script> </body> </html> ```
Markdown
복사

3.4. 사용자에게 값 입력받기

```javascript <!DOCTYPE html> <html lang="ko"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> <title>PyScript input&output</title> <link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <py-script> # html ID "input_text"와 "output_text" 와 연결된 객체 생성 input_text = Element("input_text") output_text = Element("output_text") # html 에서 생성한 ID "add_text" 의 버튼이 눌렸을 때 호출될 pys-onClick 인자로 설정된 함수 생성 def function_add_text(*args): # output_text 객체의 text 값을 input_text의 값으로 지정 output_text.element.innerText = input_text.value # 함수가 실행된 후 input_text의 값을 초기화 input_text.clear() </py-script> <main class = "container"> <h1 id = "output_text"></h1> <div> <input id = "input_text" type="text" placeholder="텍스트를 입력하세요"> <button id = "add_text" pys-onClick ="function_add_text">Click</button> </div> </main> </body> </html> ```
Markdown
복사

#참고

•
응용시
•
데모 페이지