Each time I develop stuff in Python, I get annoyed by the fact that I have to switch between these two statement in order for my scripts to work both when I import script
in a interpreted (e.g. Spyder on Ubuntu or even directly in a Python console) and in a console, when I 'launch' my scripts root@machine# python script.py
:
import os
some_input_data_path = os.path.join(os.path.dirname(os.path.dirname(__file__),'input.csv')
works when the script is launch as an executable, but not in a interpreter.
import os
some_input_data_path = os.path.join(os.path.dirname(os.getcwd()),'input.csv')
works when the script is run in a interpreter, but not when it is launched as an executable.
I have set up a convenience try:
block at the beginning of each of my scripts files to set __file__
as so:
import os
try:
__file__
except NameError:
__file__ = os.path.join(os.getcwd(), 'test.py')
print("Warning: script is not run as a module. "
"Setting '__file__' to: {}".format(__file__))
else:
pass
I wonder if there are good practices of if there is some other (better) things that I can do to work (without having to manually switch something) both within my interpreter (mainly to develop stuff), and when executing the scripts in a terminal (mainly when they are used in production)?
Use case
Using this file:
$ cat script.py
import os
some_input_data_path = os.path.join(os.path.dirname(os.getcwd()), 'input.csv')
print(some_input_data_path)
when I execute this in Spyder I got this printed:
'/home/username/scriptdir/input.csv'
which is fine.
If I execute this script in bash:
user@machine:/home/username/scriptdir$ python script.py
'/home/username/scriptdir/input.csv'
but if I cd ..
:
user@machine:/home/username$ python scriptdir/script.py
'/home/username/input.csv' # <- this is obviously no more where the csv input data file is.