3

I often develop notebooks using VSCode jupyter code cells like the one below and execute them via python script.py in tmux. The problem is that currently I don't have a function for executed_as_jupyter_code_cell and some code is executed unnecessarily. Can I check this somehow?

A workaround is to simply set a custom env variable, but maybe there's a direct solution?

#%% load

def load(x):
    ...

if executed_as_jupyter_code_cell():
    y=load(x)

#%% transform

def transform(y):
    ...

if executed_as_jupyter_code_cell():
    z=transform(y)

#%% pipe
from concurrent.futures import ProcessPoolExecutor

def pipe(x):
    y=load(x)
    z=transform(y)
    save(z)

with ProcessPoolExecutor() as exec:
    exec.map(pipe, some_long_iterable)
gebbissimo
  • 2,137
  • 2
  • 25
  • 35
  • 1
    Does this answer your question? [How can I check if code is executed in the IPython notebook?](https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook) – tevemadar Mar 07 '23 at 14:31
  • @tevemadar: When executing it via python it says `NameError: name 'get_ipython' is not defined`. My understanding is it only exists when executing it via ipython, but not via python, correct? – gebbissimo Mar 07 '23 at 15:06
  • Ah, but I could simply try something like `try: get_ipython except NameError`. Hmm... there's certainly a cleaner way here. – gebbissimo Mar 07 '23 at 15:07
  • https://stackoverflow.com/a/5377051/2135504 this should be the accepted answer – gebbissimo Mar 07 '23 at 15:08
  • 1
    Well, yes, that's also a clue: when you can't access IPython/Jupyter API-s, you're running outside. – tevemadar Mar 07 '23 at 15:08
  • I'm fine with closing this question as duplicate. I didn't immediately make the connection between VSCode code cells and ipython but it's rather obvious looking back. – gebbissimo Mar 07 '23 at 15:23
  • Revoked my close vote, one of the duplicates you've found would fit better. – tevemadar Mar 07 '23 at 15:45

1 Answers1

0

The following seems to work, but not sure how reliable it is:

import os

def executed_as_jupyter_code_cell():
    return "IPYKERNEL_CELL_NAME" in os.environ
gebbissimo
  • 2,137
  • 2
  • 25
  • 35