How to run `python -m <module>`?

157 Views Asked by At

How can I run python -m black (or pass Python code as input to main function of black to get formatted output) in Pyodide?

I'm hoping to add a "Format" button to the bottom next to "Run". How to run black is the issue. I can set the textarea contents with JavaScript.

I can install black-22.12.0-py3-none-any.whl since it is a pure Python wheel (ends with none-any.whl).

python -m <module> runs module as a script:

-m module-name
    Searches sys.path for the named module and runs the corresponding .py file as a script.

Pyodide docs:

It is possible to run arbitrary Python code and install Python wheels in Pyodide. Pyodide also has a virtual file system.

It is also possible to call black as an API, but in this case, how can I safely escape the input (by users)?

1

There are 1 best solutions below

0
On

python -m xxx just imports the module and runs it as if it were the main program. Since the __main__ part of black just says:

if __name__ == "__main__":
    patched_main()

you can simulate that by doing:

import black
black.patched_main()

The runpy.run_module API can be used to simulate python -m, but in this case I don't think you need that at all.