Search code examples
pythonjupyter-notebookpython-import

How to run Python interactive window with the -m flag in VSCode?


Explanation

VS code has this functionality named .py interactive window, which basically is jupyter notebook cells inside a .py file.

This makes my work much more efficient and easier because I cant test my modules like in Jupyter Notebook, use it as a module like .py files and also invoke it as script using python myscript.py. More detailed description here: https://code.visualstudio.com/docs/python/jupyter-support-py


Problem

Right now if i want this setup to work I have to make imports by using:

sys.path.append("path/to/my/module.py")

Is there a way I can run my modules in interactive window with the -m flag so it doesn't fail when doing relative imports?

If not, is there another standardised way that also enables me running the script using VS Code jupyter cells inside .py files without having to import packages using sys.path.append


What I have tried

Until now I have tried adding ` __init__.py ` file to each subfolder but it still doesn't work, it fails when using relative imports from interactive window.

Any help, is appreciated.


Solution

  • I ended up using poetry package manager to initialize a package and was able to import modules.

    poetry new myproject
    cd myproject
    poetry install
    touch myproject/file.py
    

    How to import in Python

    from myproject.file import whatever
    
    whatever()