How to use multiple python files

Hello,

I would like to refactor my code in several python files and therefore use functions written in a .py file from another .py file. The two python files are in the same directory, so I try to import the file with the “import …” syntax but a ModuleNotFoundError is raised.

Can anyone tell me if what I want to do is possible and how?

Thanks!

Yes indeed! If you add the <py-config> element to the page, you can use one of its parameters to load files from the network into the Emscripten local file system that Pyodide creates “within the browser window”, so to speak. This local file system is where Python looks for files when using import.

Let’s say we want to load a file from the url some/url/to/mymodule.py to a file located at ./mymodule.py in the local filesystem. That is to say, in the same folder that Python scripts are executed from.

In the current release (2022.09.1), the syntax is:

<!-- PyScript 2022.09.1 -->
<py-config>
    paths = ['some/url/to/mymodule.py']
</py-config>
<py-script>
    import mymodule
</py-script>

The upcoming release (2022.12.1 probably) introduces a powerful new feature called “Fetch Configurations”; there are a few ways to get the file where it’s wanted with a fetch configuration, but for this URL and destination, one solution is:

<!-- PyScript 2022.12.1 (probably) -->
<py-config>
    [[fetch]]
    from = 'some/url/to'
    files = ['mymodule.py']
</py-config>
<py-script>
    import mymodule
</py-script>
1 Like

Thank you for your quick response!

It was quite simple after all. However, I can’t use a Pyscript function such as Element(‘…’).write(‘…) :’(

I saw that this problem was raised on github (issue 525):

Do you know if it is possible today to make calls to Element from the side script?

In the upcoming release, it will be possible to use import pyscript or from pyscript import Element etc. thanks to some work done around PR #961.

That next release is coming quite soon! Release Candidate 1 is out now: PyScript 2022.12.1.RC1. Feel free to check it out.

1 Like

Thanks, I’ll keep an eye on it! :wink:

i use your code @JeffGlass

<py-config>
  [[fetch]]
  files = ['example.py']
  from = '../wp-content/themes/codetheme/py/'
</py-config>
<py-script>
  import example
  example.hello()
</py-script>

AttributeError: module ‘example’ has no attribute ‘hello’

#!/var/www/u0745362/data/env/bin/python
import cgi

print("Content-type: text/html\n")

def hello():
   print("ok")

if i’m use code on server side without pyscript between two py-files and import module from one to second file it works fine

 import example
  example.hello()