Python snippets
December 10, 2018
How to reliably get folder path of what script we are in right now:
here = pathlib . Path ( __file__ ). parent . absolute ()
here = os. path . abspath (os. path . dirname ( __file__ ))
Pathlib returns a path object , os returns a string:
WindowsPath('T:/ENV.558/scratch/merge-rgb-nir')
T:\\ENV.558\\scratch\\merge-rgb-nir
from inspect import getsourcefile
here = os.path.dirname(os.path.abspath(getsourcefile(lambda:0)))
How do I get the path of the current executed file in Python?
https://stackoverflow.com/a/18489147/14420
this solution is robust even in executables
import inspect, os.path
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
https://stackoverflow.com/a/44592299/14420
#Py3
HERE = pathlib.Path(__file__).parent.absolute()
os.chdir(HERE)
import inspect, os.path, pathlib
filename = inspect.getframeinfo(inspect.currentframe()).filename
filepath = os.path.dirname(os.path.abspath(filename))
filedir = pathlib.Path(__file__).parent.absolute()
…
import socket
socket.gethostbyname_ex(socket.gethostname())
('ENV-Y225411.YNet.gov.yk.ca', [], ['199.247.217.109'])
From < https://github.com/jupyter/notebook/issues/1927 >
Leo snippets
# this doesn't work. not sure why.
if not ctypes.windll.shell32.IsUserAnAdmin():
g.es_print("No admin privileges. Start Leo as administrator first and then run this script")
subprocess.run([sys.executable,
os.path.join(here, 'elevate.py'),
os.path.abspath(getsourcefile(lambda:0))
])