Search code examples
visual-studio-codejupyteripythonipython-magic

How do I use Jupyter/IPython magic commands in VSCode?


I saw someone else using magic commands in VSCode, but when I try them, I get a syntax error. How do I get them to work?

Note: The idea for this question came from an earlier question with a similar title ("Do jupyter magic commands work on VS Code?") where the actual problem was unrelated. I'm not genuinely asking, this is just a likely scenario that could lead a VSCode beginner to ask the same question, similar to a canonical question.


Solution

  • You need to use the Jupyter extension. Then you can use a notebook or interactive window to run IPython code, including magics as well as shell commands.

    You can also keep your IPython code in a script and run it in an interactive window with the Jupyter extension, but it'll still be flagged as invalid syntax, so to avoid that, you can enable the setting magicCommandsAsComments "Uncomment shell assignments (#!), line magic (#!%) and cell magic (#!%%) when parsing code cells", for example:

    # %%
    # ! %cd
    # ! %pwd
    
    # %%
    import time
    
    # %%
    # ! %%timeit
    time.sleep(1)
    
    # %%
    # ! echo hello world!
    
    • Note: # %% is the cell delimiter