How can I run my Python projects with imports of my own codes?

143 views Asked by At

I want to run a game project of my own (text interface only) using pyodide. But I can't deal very well with the nested imports of my game, pyodide always reports the error " No module called found.

I will give an example in a smaller project that gives the same error.

display.py

import hello

def main():
    hello.talk_hello()
main()

hello.py

def talk_hello():
    print("Hello!")

script running pyodide

<script type="text/javascript">
      async function main() {
        let pyodide = await loadPyodide();
        return pyodide;
      }
      let pyodideReadyPromise = main();
      
      // Pyodide - carregar arquivos e executar chamada
      async function evaluatePython() {
        let pyodide = await pyodideReadyPromise;
        try {
          let python_code = (await (await fetch('display.py')).text());
          await pyodide.runPythonAsync(python_code)
        } catch (err) {
          console.log(err);
        }
      }
      evaluatePython();
    </script>

Pyodide error

PythonError: Traceback (most recent call last): File "/lib/python311.zip/_pyodide/_base.py", line 571, in eval_code_async await CodeRunner( File "/lib/python311.zip/_pyodide/_base.py", line 394, in run_async coroutine = eval(self.code, globals, locals) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "", line 1, in ModuleNotFoundError: No module named 'hello'

I expect all imports, whether official or part of my file, to be loaded into pyodide. Because it will only fetch the file that I directly insert.

2

There are 2 answers

2
Sand On

Not the BEST way to fix this, but for a small project you can indicate where the module that you've written lives by setting the current directory to it, and then try to import. It would look something like:

import os
os.chdir(r"path\to\the\folder\containing\your\.pyfiles")

import hello
hello.talk_hello()

Additionally, if you want to load in everything and not have to call the hello module, you could write it as:

import os
os.chdir(r"path\to\the\folder\containing\your\.pyfiles")

from hello import *
talk_hello()
2
younes On

you need add hello.py to a package : Create a new folder(hello_package) and create a file named __init__.py inside it and Put "hello.py" in it and then write import like this

in display.py:

from .hello_package import hello

def main():
    hello.talk_hello()