Skip to main content

Command Palette

Search for a command to run...

Workaround for Pyscript Importing Folder by Compiling Wheel

Updated
1 min read

2024/03/24: Updated for new version of py-config

Why

Currently, we cannot import a folder of python package in pyscript, for example:

├── index.html
├── myapp8763
│   ├── init.py
│   └── funcs.py

The below script will result in error.

<py-script>
  import myapp8763.funcs # can't find package myapp8763
  myapp8763.funcs.main()
</py-script>

The user can only import single file and use it like importing a single file.

<py-script>    
  import funcs
  funcs.main()
</py-script>

But it breaks package.

Workaround

Pyscript provide another method: Importing a wheel

{
    "packages": ["./dist/myapp8763-0.0.1-py3-none-any.whl"]
}

If we want to import a folder, we should compile a wheel file.

Structure

.
├── index.html
├── myapp8763
│   ├── init.py
│   └── funcs.py
└── setup.py

Compile wheel

To compile a package as a wheel, we need setup.py:

import setuptools

setuptools.setup(
    name='myapp8763',
    version='0.0.1',
    packages=setuptools.find_packages('.'),
    package_dir={
        'myapp8763': 'myapp8763',
    },
    setup_requires=['wheel'],
)

After compiling wheel:

python3 setup.py build bdist_wheel

We can find wheel file is generate in dist folder:

├── dist
│   └── myapp8763-0.0.1-py3-none-any.whl

Include and Use

pyscript.json:


{
    "packages": ["./dist/myapp8763-0.0.1-py3-none-any.whl"]
}

index.html:

<script type="py" config="./pyscript.json">
  import myapp8763.funcs
  myapp8763.funcs.main()
</script>

Code

The whole code is here: https://github.com/mudream4869/pyscript-local-package

Ref

More from this blog

簡介 C++ 的 Type Erase (用多型和模板做 Duck Type)

起點 讓我們先從 template 出發:foo 需要一個 callback function。 template<typename Func> void foo(Func callback) { // ... callback(); } 但是這會讓編譯錯誤訊息有點模糊:假如 callback 並不是一個可以呼叫的函數指標,或者並不是一個 callable object ,那編譯器會說錯出在第四行。但是我們都希望,編譯器在呼叫函數時就幫我們指出:這不是 foo 想要的 call...

May 14, 20243 min read

帕秋莉的魔法筆記

45 posts

後端工程師。

不定時張貼一些寫扣時的筆記。