Reputation: 497
I was looking through methods of handling arguments when I realised that I'm actually looking to do something slightly different.
Basically I am writing my python3 script in Jupyter as foo.ipynb
to test it on small datasets, and to share it with my team easily, but I will also be exporting the script to foo.py
and running it on our cluster for the bigger datasets. I would like it to have some different behaviours, like getting a filepath from an argument or not, depending on how the script was ran.
Is there any way for a python script to know if it was ran in a Jupyter notebook or through the command line? Our cluster uses slurm, so foo.py
will be called from a bash script, is there any way to handle that as well?
Upvotes: 0
Views: 63
Reputation: 4837
You can use __file__
(Python doc).
When calling foo.py
directly via python foo.py
then __file__
will be set, e.g.: foo.py
with only a print(__file__)
will output foo.py
.
If called in Jupyter it won't be set.
Regarding slurm, I'd recommend passing in another argument to your script to distinguish this, e.g. foo.py --slurm
with argparse.
Code Addendum:
if '__file__' in locals():
print(__file__)
else:
print('__file__ not set')
Upvotes: 1