0

I would like to use a commandline tool (jupytext) inside a Python file. In a console, it works like this, which makes a .ipynb file out of .py

jupytext --to notebook notebook.py

But I don't want to do it for every file in a console. How can I execute this, when running a Python file itself (.py) in order to generate .ipynb automatically?

On a side note, I came across subprocess, which works fine with UNIX command in a python file, but I am not sure how to apply it for my case:

import subprocess
list_of_files = subprocess.run(['ls', '-la'], capture_output=True, text=True)
print(list_of_files.stdout)

Thanks a lot!

user7665853
  • 195
  • 1
  • 15

1 Answers1

1

Something like this?

import glob
import subprocess

for py in glob("*.py"):
    subprocess.run(
        ["jupytext", "--to", "notebook", py]
        check=True)

However, jupytext has a Python API too, so it's better to call that directly from Python for a more efficient solution, and more control over the process, too.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Associated question is useful but not exacly answer my question. So, I made an answer below. Many thanks for @tripleee. You code is not exactly working, but you made a right reference and I made it from there! Only a bit of workaround I found is that this library only works in Juypter notebook (thus it did not work in Python file). – user7665853 Jun 30 '22 at 13:59
  • So, my solution was ```import glob import jupytext for py in glob.glob('*.py'): ntbk = jupytext.read(py) py2 = py.replace('.py', '.ipynb') jupytext.write(ntbk, py2)``` – user7665853 Jun 30 '22 at 14:00