杰瑞科技汇

Python Transcrypt如何实现跨平台编译?

Of course! Let's dive deep into Transcrypt, a powerful and popular Python-to-JavaScript compiler.

What is Transcrypt?

Transcrypt is a source-to-source compiler. Its main job is to take your Python code and translate it into clean, readable, and efficient JavaScript that can run in any web browser or in Node.js.

The key philosophy is: Write Python, Run JavaScript.

You get to use the Python syntax, its vast standard library (or at least a significant part of it), and your favorite Python tools, while the code executes in the JavaScript ecosystem, giving you access to the entire web platform.


How Does It Work? (The Core Concept)

Transcrypt works in two main steps:

  1. Compilation (Python to JavaScript): You run the Transcrypt compiler on your Python modules (.py files). It parses the Python code and translates it into JavaScript. This JavaScript is designed to be interoperable with native JavaScript.
  2. Execution (JavaScript in the Browser): The generated JavaScript, along with any native JavaScript libraries or code you've written, is loaded into a web page. The browser's JavaScript engine executes it.

Crucially, Transcrypt doesn't just create a single JavaScript file. It creates a modular system. Each Python module becomes a JavaScript module, allowing for clean code organization and efficient loading.


A Simple "Hello World" Example

Let's walk through the most basic example to see it in action.

Step 1: Installation

First, you need to install Transcrypt. It's a Python package, so you'll need Python and pip.

pip install transcrypt

Step 2: Write the Python Code

Create a file named hello.py.

# hello.py
def greet(name):
    return f"Hello, {name} from Python!"
# This will be the entry point of our application
if __name__ == '__main__':
    message = greet("World")
    print(message)

Step 3: Compile the Python Code

Now, use the Transcrypt command-line tool to compile your Python file.

transcrypt -r -n -p /usr/bin/python3 hello.py

Let's break down those flags:

  • -r: Run the compiled code in the browser after compilation.
  • -n: No run. Just compile. We'll use this for our next step.
  • -p /usr/bin/python3: Specifies the Python interpreter to use. This is important for ensuring compatibility.

After running this, Transcrypt creates a __javascript__ directory.

.
├── __javascript__
│   ├── __builtin__.js
│   ├── hello.js
│   └── hello__.js
└── hello.py
  • hello.js: This is the compiled version of your hello.py file.
  • hello__.js: This is a "stub" file that helps with Python's module system. You generally don't edit it.
  • __builtin__.js: This contains the implementation of Python's built-in functions and types (like print, len, dict, etc.) in JavaScript.

Step 4: Create the HTML File

To see the result, you need an HTML file that loads the generated JavaScript. Create index.html.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">Transcrypt Hello World</title>
</head>
<body>
    <h1>Check the browser's developer console!</h1>
    <!-- Load the compiled Python module -->
    <script src="__javascript__/hello.js"></script>
</body>
</html>

Step 5: Run in the Browser

Open index.html in your web browser and open the Developer Console (usually with F12 or Ctrl+Shift+I). You will see the output:

Hello, World from Python!

Key Features and Benefits

  1. Native JavaScript Output: The generated JS is clean and not wrapped in a heavy runtime. It uses modern JavaScript features and can be easily minified and bundled with tools like Webpack or Rollup.
  2. Full Python Standard Library Support: Transcrypt implements a significant portion of the Python standard library in JavaScript. You can use things like math, datetime, json, collections, and itertools directly.
  3. Seamless Interoperability: This is one of Transcrypt's strongest points.
    • Calling JavaScript from Python: You can import and use native JavaScript libraries.
    • Calling Python from JavaScript: You can call your Python functions directly from JavaScript.
  4. Tooling Ecosystem: You can use your favorite Python linters (like pylint or flake8) and IDEs on your Python code. This makes development feel very natural.
  5. Modularity: The output is modular, making it easy to integrate into larger JavaScript projects.

Advanced Example: Interoperability

Let's see how Python and JavaScript can talk to each other.

Calling JavaScript from Python

Imagine you want to use a popular JavaScript library like lodash. First, you'd include it in your HTML.

<!-- index.html -->
...
<body>
    <h1>Check the browser's developer console!</h1>
    <!-- Load the external JS library -->
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
    <!-- Load our compiled Python -->
    <script src="__javascript__/interop.js"></script>
</body>
...

Now, create a Python file interop.py to use lodash.

# interop.py
# Transcrypt provides a way to import JS modules
from browser import window
# Get the lodash object from the global window
lodash = window._ 
# Now you can use lodash functions as if they were Python functions
my_list = [1, 2, 3, 2, 1]
# Use lodash's 'uniq' function
unique_list = lodash.uniq(my_list)
print(f"Original list: {my_list}")
print(f"Unique list (from lodash): {unique_list}")
# You can also access JS DOM elements
document = window.document
heading = document.querySelector('h1')
heading.style.color = 'blue'
heading.textContent = "Lodash and DOM accessed from Python!"

Compile and run it. You'll see the output in the console and the style of the heading will change.

Calling Python from JavaScript

Transcrypt automatically exports your Python functions to the global JavaScript scope. You just need to know the naming convention.

Your Python file interop.py:

# interop.py
def add_python(a, b):
    return a + b
# A class
class Greeter:
    def __init__(self, name):
        self.name = name
    def say_hello(self):
        return f"Hello, I am {self.name}, a Python object."

Your HTML file index.html:

<!-- index.html -->
...
<body>
    <h1>Open the console!</h1>
    <script src="__javascript__/interop.js"></script>
    <script>
        // Transcrypt exports modules to a global '__main__' object
        // For a file 'interop.py', the module is 'interop__'
        // Call the Python function
        let sum = __main__.interop__.add_python(5, 10);
        console.log(`Sum from Python function: ${sum}`);
        // Use the Python class
        let greeter = new __main__.interop__.Greeter("JavaScript");
        let message = greeter.say_hello();
        console.log(message);
    </script>
</body>
...

Transcrypt vs. Other Solutions

Feature Transcrypt Pyodide (Emscripten) Brython
How it Works Source-to-source Compiler (Python -> JS) Binary Compiler (CPython WASM port) Interpreter (Python parser written in JS)
Performance Very High. Generates native JS. High. Leverages CPython's speed. Medium. Interpreting in JS has overhead.
Python Stdlib Large subset, implemented in JS. Full. It's the real CPython. Large subset, implemented in JS.
Output Clean, readable JS. A single large WASM file. JS files and a runtime.
Use Case Building new web apps with Python syntax; integrating into JS projects. Data science, scientific computing in the browser. Quick prototyping, embedding small scripts.
"Pythonic Feel" High. You write idiomatic Python. High. It's the real deal. High. You write idiomatic Python.

When to choose Transcrypt:

  • You want to build a modern, performant web application.
  • You are part of a JavaScript team and want to introduce Python for certain parts of the codebase.
  • You need clean, maintainable JavaScript output that can be easily integrated with existing toolchains (Webpack, Vite, etc.).
  • You value the ability to use Python's standard library without a heavy runtime.

Limitations

  • Not All Python is Supported: You can't use C-extensions or libraries that rely on CPython's C API. You are limited to what can be compiled to JavaScript or what can be bridged via interoperability.
  • Learning Curve: While Python syntax is easy, understanding the nuances of the Transpiler and the Python-to-JS mapping (especially for things like self vs. this) takes some time.
  • The __main__ Module: Calling Python from JavaScript requires using the __main__.module_name convention, which can feel a bit clunky at first.

Conclusion

Transcrypt is an excellent tool for developers who want to leverage the power and expressiveness of Python for web development without leaving the performance and ecosystem of JavaScript. It strikes a fantastic balance between "Pythonic" development and "Native" web performance, making it a strong contender for modern web projects.

分享:
扫描分享到社交APP
上一篇
下一篇