Search code examples
pythonpython-3.xangularangular8brython

Import a library of Python's standard distribution using Brython 3.7.5 into Angular8 project


I'm doing the first experiments with Angular and Brython. Everything started working, then strangely Python's standard libraries were not recognized. I'm curious to know why.

This is the html part (index.html in angular8):

<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>HelloWorld</title>
        <base href="/">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body onload = "brython()">
        <app-root></app-root>

        <script type="text/python">
            import os
        </script>
    </body>
</html>

These are the scripts linked in the angular.json file

"scripts": [
    "src/assets/js/script.js",
    "src/assets/js/brython.js",
    "src/assets/js/brython_stdlib.js"
]

Why, despite linking (presumably) Python's stdlib, the treceback remains:

ImportError: No module named os

Did I forget to put something else, or is this problem unsolvable? In the sense that you can't use Brython in angular8?


Solution

  • I suspect the search mechanism described in the https://brython.info/static_doc/en/faq.html is failing:

    Q : I see a lot of 404 errors in the browser console when I run Brython scripts, why is that ?

    A : this is because of the way Brython implements the "import" mechanism. When a script has to import module X, Brython searches for a file or a package in different directories : the standard library (directory libs for Javascript modules, Lib for Python modules), the directory Lib/site-packages, the directory of current page. For that, Ajax calls are sent to the matching urls; if the file is not found, the 404 error message is written in the browser console, but the error is caught by Brython which goes on searching until it finds the module, or raises ImportError if all paths have been tried with no result

    which implies the installation is not quite right. Did you check the console for errors?

    There is a page which describes the expected layout; in short, the rules are very similar to the rules for normal Python.