Program Tip

Python을 WebAssembly로 컴파일

programtip 2020. 12. 4. 20:23
반응형

Python을 WebAssembly로 컴파일


Python 2.7 코드를 웹 어셈블리로 변환 할 수 있다고 읽었지만 그 방법에 대한 확실한 가이드를 찾을 수 없습니다.

지금까지 Emscripten과 필요한 모든 구성 요소를 사용하여 웹 어셈블리에 C 프로그램을 컴파일 했으므로 작동하고 있음을 알고 있습니다 (사용 된 가이드 : http://webassembly.org/getting-started/developers-guide/ )

Ubuntu 컴퓨터에서이 작업을 수행하기 위해 수행해야하는 단계는 무엇입니까? 파이썬 코드를 LLVM 비트 코드로 변환 한 다음 Emscripten을 사용하여 컴파일해야합니까? 그렇다면 어떻게해야합니까?


WebAssembly 대 asm.js

먼저, 원칙적으로 WebAssemblyasm.js어떻게 다른지 , 기존 지식과 도구를 재사용 할 가능성이 있는지 살펴 보겠습니다 . 다음은 꽤 좋은 개요를 제공합니다.

요약하자면 WebAssembly ( 대략 로드맵에 더 많은 것이 있으므로 MVP ) :

  • 기존 JavaScript 엔진 (따라서 JIT 가능 또는 컴파일 된 AOT)에 의해 실행될 수있는 정적 유형이있는 AST의 이진 형식입니다.
  • 10-20 % 더 간결하고 (gzipped 비교) 자바 스크립트보다 훨씬 빠르게 파싱합니다.
  • JavaScript 구문에 맞지 않는 더 낮은 수준의 작업을 표현할 수 있으며 asm.js (예 : 64 비트 정수, 특수 CPU 명령, SIMD 등)를 읽을 수 있습니다.
  • asm.js로 (일부) 변환 가능합니다.

따라서 현재 WebAssembly는 asm.js의 반복이며 C / C ++ 만 대상으로합니다.

웹에서의 Python

GC가 Python 코드가 WebAssembly / asm.js를 대상으로하는 것을 막는 유일한 것 같지 않습니다. 둘 다 Python 코드를 (실제적으로) 표현할 수없는 저수준 정적으로 형식화 된 코드를 나타냅니다. 현재 WebAssembly / asm.js의 툴체인은 LLVM 기반이므로 LLVM IR로 쉽게 컴파일 할 수있는 언어를 WebAssembly / asm.js로 변환 할 수 있습니다. 그러나 슬프게도 Python은 Unladen SwallowPyPy의 여러 시도의해 입증 된 것처럼 너무 동적으로 적용 할 수 없습니다 .

이 asm.js 프레젠테이션에는 동적 언어의 상태에 대한 슬라이드가 있습니다 . 이것이 의미하는 바는 현재 전체 VM (C / C ++의 언어 구현)을 WebAssembly / asm.js로 컴파일하고 가능한 경우 JIT로 원본 소스를 해석하는 것만 가능하다는 것입니다. Python의 경우 기존 프로젝트가 여러 개 있습니다.

  1. PyPy : PyPy.js ( PyCon에서 작성자의 이야기 ). 여기에 릴리스 저장소가 있습니다. 기본 JS 파일 pypyjs.vm.js은 13MB (2MB 이후 gzip -6) + Python stdlib + 기타 항목입니다.
  2. CPython : pyodide , EmPython , CPython-Emscripten , EmCPythonempython.js5.8MB ( 이후 2.1MBgzip -6 )이며 stdlib는 없습니다.
  3. Micropython : 이 포크 .

    거기에는 빌드 된 JS 파일이 없었기 때문에 trzeci/emscripten/기성품 인 Emscripten 툴체인 으로 빌드 할 수있었습니다 . 다음과 같은 것 :

    git clone https://github.com/matthewelse/micropython.git
    cd micropython
    docker run --rm -it -v $(pwd):/src trzeci/emscripten bash
    apt-get update && apt-get install -y python3
    cd emscripten
    make -j
    # to run REPL: npm install && nodejs server.js 
    

    그것은 생산 micropython.js1.1 MB (후 2백25킬로바이트의 gzip -d). stdlib없이 매우 호환되는 구현 만 필요한 경우 후자는 이미 고려할 사항입니다.

    WebAssembly 빌드를 생성하려면 13 행을 다음 Makefile으로 변경할 수 있습니다.

    CC = emcc -s RESERVED_FUNCTION_POINTERS=20 -s WASM=1
    

    그런 다음 다음을 make -j생성합니다.

    113 KB micropython.js
    240 KB micropython.wasm
    

    의 HTML 출력 emcc hello.c -s WASM=1 -o hello.html을보고 이러한 파일을 사용하는 방법을 확인할 수 있습니다.

    이런 식으로 WebAssembly에서 PyPy 및 CPython을 잠재적으로 빌드하여 호환 브라우저에서 Python 애플리케이션을 해석 할 수도 있습니다.

여기서 흥미로운 또 다른 점은 Python to C ++ 컴파일러 인 Nuitka 입니다. 잠재적으로 Python 앱을 C ++로 빌드 한 다음 Emscripten을 사용하여 CPython과 함께 컴파일 할 수 있습니다. 그러나 실제로 나는 그것을하는 방법을 모릅니다.

솔루션

당분간 수 메가 바이트 크기의 JS 파일을 다운로드 할 수없는 기존 웹 사이트 또는 웹 앱을 구축하는 경우 Python-JavaScript 트랜스 파일러 (예 : Transcrypt ) 또는 JavaScript Python 구현 (예 : Brython)을 살펴보십시오. ). 또는 JavaScript로 컴파일되는 언어 목록 에서 다른 사람들과 함께 행운을 시험해보십시오 .

그렇지 않고 다운로드 크기가 문제가되지 않고 많은 거친 가장자리를 해결할 준비가 되었다면 위의 세 가지 중에서 선택하십시오.


This won't be possible until web assembly implements garbage collection. You can follow progress here: https://github.com/WebAssembly/proposals/issues/16


In short: you can't convert arbitrary Python to Web Assembly, and I doubt you will be able to for a long time to come. A workaround might be Python to C to Web Assembly, but that isn't generally going to work either since Python-to-C is fragile (see below).

WebAssembly is specifically targeted to C-like languages as you can see at http://webassembly.org/docs/high-level-goals/

Translating from Python to C can be done with tools like PyPy, which has been under development for a long time, but which still does not work for arbitrary Python code. There are several reasons for this:

1) Python has some very handy, abstract and nice data structures, but they are hard to translate into static code. 2) Python depends on dynamic garbage collection. 2) Most Python code depends heavily on various libraries, each of which has it's own quirks and issues (such as being written in C, or even assembler).

If you look more carefully into why Python-to-C (or Python to C++) has been so tricky you can see the detailed reasons behind this terse answer, but I think that's outside the scope of your question.

참고URL : https://stackoverflow.com/questions/44761748/compiling-python-to-webassembly

반응형