Search code examples
pythonpyodide

How to copy / download file created in Pyodide in browser?


I managed to run Pyodide in browser. I created hello.txt file. But how can I access it.
Pyodide
https://github.com/iodide-project/pyodide/blob/master/docs/using_pyodide_from_javascript.md

pyodide.runPython('open("hello.txt", "w")')

What I tried in chrome devtools?

pyodide.runPython('os.chdir("../")')
pyodide.runPython('os.listdir()')
pyodide.runPython('os.path.realpath("hello.txt")')

Output for listdir

["hello.txt", "lib", "proc", "dev", "home", "tmp"]

Output for realpath

"/hello.txt"

Also,

pyodide.runPython('import platform')
pyodide.runPython('platform.platform()')

Output

"Emscripten-1.0-x86-JS-32bit"

All outputs in chrome devtools console.

It is created in root folder. But how it can be accessed in file explorer or anyway to copy file to Download folder?

Thanks


Solution

  • Indeed pyodide operates in an in-memory (MEMFS) filesystem created by Emscripten. You can't directly write files to disk from pyodide since it's executed in the browser sandbox.

    You can however, pass your file to JavaScript, create a Blob out of it and then download it. For instance, using,

    let txt = pyodide.runPython(`                  
        with open('/test.txt', 'rt') as fh:
            txt = fh.read()
        txt
    `);
    const blob = new Blob([txt], {type : 'application/text'});
    let url = window.URL.createObjectURL(blob);
    window.location.assign(url);
    

    It should have been also possible to do all of this from the Python side, using the type conversions included in pyodide, i.e.

    from js import Blob, document
    from js import window
      
    with open('/test.txt', 'rt') as fh:
        txt = fh.read()
        
    blob = Blob.new([txt], {type : 'application/text'})
    url = window.URL.createObjectURL(blob) 
    window.location.assign(url)
    

    however at present, this unfortunately doesn't work, as it depends on pyodide#788 being resolved first.