Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ff5ab7a

Browse files
authored
Merge pull request pyscript#13 from anaconda/pys-7/support_local_imports
support local imports
2 parents 1966f1c + a9e1b7c commit ff5ab7a

File tree

7 files changed

+73
-14
lines changed

7 files changed

+73
-14
lines changed

pyscriptjs/examples/repl2.html

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@
1212
<script defer src="../build/pyscript.js"></script>
1313
</head>
1414

15+
<py-env>
16+
- bokeh
17+
- numpy
18+
- paths:
19+
- /utils.py
20+
</py-env>
21+
1522
<body>
1623
<div class="w-full h-full">
1724
<div class="flex">

pyscriptjs/examples/simple_script2.html

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,27 +10,29 @@
1010
<link rel="stylesheet" href="../build/pyscript.css" />
1111

1212
<script defer src="../build/pyscript.js"></script>
13+
<py-env>
14+
- paths:
15+
- /utils.py
16+
</py-env>
1317
</head>
1418

1519
<body>
1620
<div class="font-mono">start time: <label id="outputDiv"></label></div>
1721
<div id="outputDiv2" class="font-mono"></div>
1822
<div id="outputDiv3" class="font-mono"></div>
1923
<py-script target="outputDiv">
20-
from datetime import datetime
21-
now = datetime.now()
22-
now.strftime("%m/%d/%Y, %H:%M:%S")
24+
import utils
25+
utils.now()
2326
</py-script>
2427

2528
<py-script>
26-
from datetime import datetime
29+
from utils import now
2730
import asyncio
2831

2932
async def foo():
3033
while True:
3134
await asyncio.sleep(1)
32-
now = datetime.now()
33-
output = now.strftime("%m/%d/%Y, %H:%M:%S")
35+
output = now()
3436
pyscript.write("outputDiv2", output)
3537

3638
out3 = Element("outputDiv3")

pyscriptjs/examples/todo.html

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@
1010
<link rel="stylesheet" href="/build/pyscript.css" />
1111

1212
<script defer src="/build/pyscript.js"></script>
13+
<py-env>
14+
- paths:
15+
- /utils.py
16+
</py-env>
1317
</head>
1418

1519
<body class="container">
@@ -22,14 +26,14 @@
2226
<div class="text-center w-full mb-8">
2327
<h1 class="text-3xl font-bold text-gray-800 uppercase tracking-tight">To Do List</h1>
2428
</div>
25-
2629
<div>
2730
<input id="new-task-content" class="border flex-1 mr-3 border-gray-300 p-2 rounded" type="text">
2831
<button id="new-task-btn" class="p-2 text-white bg-blue-600 border border-blue-600 rounded" type="submit" pys-onClick="add_task">
2932
Add task
3033
</button>
3134
</div>
3235

36+
<py-list id="myList"></py-list>
3337
<div id="list-tasks-container" class="flex flex-col-reverse mt-4">
3438
</div>
3539

pyscriptjs/examples/todo.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from datetime import datetime as dt
2+
from utils import add_class, remove_class
23
from js import console
34

45
tasks = []
@@ -12,6 +13,7 @@ def add_task(*ags, **kws):
1213
# create task
1314
task_id = f"task-{len(tasks)}"
1415
task = {"id": task_id, "content": new_task_content.element.value, "done": False, "created_at": dt.now()}
16+
1517
tasks.append(task)
1618

1719
# add the task element to the page as new node in the list by cloning from a template
@@ -24,14 +26,13 @@ def add_task(*ags, **kws):
2426
def check_task(evt=None):
2527
task['done'] = not task['done']
2628
if task['done']:
27-
taskHtmlContent.element.classList.add("line-through")
29+
add_class(taskHtmlContent, "line-through")
2830
else:
29-
taskHtmlContent.element.classList.remove("line-through")
31+
remove_class(taskHtmlContent, "line-through")
3032

3133
new_task_content.clear()
3234
taskHtmlCheck.element.onclick = check_task
3335

3436
def add_task_event(e):
35-
console.log("im in")
3637
if (e.key == "Enter"):
3738
add_task()

pyscriptjs/src/components/pyenv.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as jsyaml from 'js-yaml';
22

33
import { pyodideLoaded, loadedEnvironments, mode, addInitializer } from '../stores';
4-
import { loadPackage } from '../interpreter';
4+
import { loadPackage, loadFromFile } from '../interpreter';
55

66
// Premise used to connect to the first available pyodide interpreter
77
let pyodideReadyPromise;
@@ -37,13 +37,36 @@ export class PyEnv extends HTMLElement {
3737
this.code = this.innerHTML;
3838
this.innerHTML = '';
3939

40-
let env = this.environment = jsyaml.load(this.code);
40+
let env = [];
41+
let paths = [];
42+
this.environment = jsyaml.load(this.code);
43+
for (let entry of this.environment) {
44+
if (typeof entry == "string" ){
45+
env.push(entry);
46+
}
47+
else if (entry.hasOwnProperty('paths')){
48+
for (let path of entry.paths) {
49+
paths.push(path);
50+
}
51+
}
52+
}
53+
4154
async function loadEnv() {
4255
let pyodide = await pyodideReadyPromise;
4356
await loadPackage(env, pyodide);
4457
console.log("enviroment loaded")
4558
}
59+
60+
async function loadPaths() {
61+
let pyodide = await pyodideReadyPromise;
62+
for (let singleFile of paths) {
63+
await loadFromFile(singleFile, pyodide);
64+
}
65+
console.log("paths loaded")
66+
}
4667
addInitializer(loadEnv);
68+
addInitializer(loadPaths);
4769
console.log("enviroment loading...", env)
70+
4871
}
4972
}

pyscriptjs/src/interpreter.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { getLastPath } from "./utils";
2+
13
// @ts-nocheck
24
// @ts-ignore
35
let pyodideReadyPromise;
@@ -129,4 +131,18 @@ let loadPackage = async function(package_name: string[] | string, runtime: any):
129131
await runtime.loadPackage(package_name);
130132
}
131133

132-
export {loadInterpreter, pyodideReadyPromise, loadPackage}
134+
let loadFromFile = async function(s: string, runtime: any): Promise<any> {
135+
let filename = getLastPath(s);
136+
await runtime.runPythonAsync(`
137+
from pyodide.http import pyfetch
138+
139+
response = await pyfetch("`+s+`")
140+
content = await response.bytes()
141+
with open("`+filename+`", "wb") as f:
142+
f.write(content)
143+
`)
144+
145+
runtime.pyimport(filename.replace(".py", ""));
146+
}
147+
148+
export {loadInterpreter, pyodideReadyPromise, loadPackage, loadFromFile}

pyscriptjs/src/utils.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11

2-
export function addClasses(element: HTMLElement, classes: Array<string>){
2+
function addClasses(element: HTMLElement, classes: Array<string>){
33
for (let entry of classes) {
44
element.classList.add(entry);
55
}
66
}
7+
8+
const getLastPath = function (str) {
9+
return str.split('\\').pop().split('/').pop();
10+
}
11+
12+
export {addClasses, getLastPath}

0 commit comments

Comments
 (0)