Reputation: 2944
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).
Upvotes: 3
Views: 1417
Reputation: 5426
tqdm
now has an autonotebook
module. From the doc:
It is possible to let tqdm automatically choose between console or notebook versions by using the autonotebook submodule:
from tqdm.autonotebook import tqdm
tqdm.pandas()
Note that this will issue a TqdmExperimentalWarning
if run in a notebook since it is not meant to be possible to distinguish between jupyter notebook and jupyter console. Use auto instead of autonotebook to suppress this warning.
Upvotes: 5
Reputation: 2944
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
Upvotes: 2