Search code examples
pythonipythonjupyter-notebookspydertqdm

tqdm variations in different python enviroments


I'm working with tqdm package that presents progress bar in python.

tqdm has also a widget for Jupyter notebooks (tqdm_notebook()), allowing a pretty "web-ish" progress bar.

My problem that I have a tqdm progress bar inside a code.py file, that I import into jupyter notebook.

While running the code.py from regular python eviroment (i.e. Ipython, IDLE, shell) I want tqdm to run in normal form:

from tqdm import tqdm
a = 0
for i in tqdm(range(2000)):
   a+=i

but when I import code.py into Jupyter, I want it to use tqdm_notebook():

from tqdm import tqdm_notebook as tqdm
a = 0
for i in tqdm(range(2000)):
   a+=i

How can I make python distinguish between the environments?

I found this post that suggest to check get_ipython().__class__.__name__ or 'ipykernel' in sys.modules but it doesn't distinguish between the notebook and other Ipython shells (such as in Spyder or IDLE).


Solution

  • Apparently, using sys.argv can help here.

    import sys
    print sys.argv
    

    Running this code in Jupyter will have this arguments:

    ['C:\\Users\\...\\lib\\site-packages\\ipykernel\\__main__.py',
     '-f',
     'C:\\Users\\...\\jupyter\\runtime\\kernel-###.json']
    

    While of course running from shell/IDLE won't have the jupyter line.

    Therefore the import statement in code.py should be:

    if any('jupyter' in arg for arg in sys.argv):
        from tqdm import tqdm_notebook as tqdm
    else:
       from tqdm import tqdm