trace the stack when root finding gets desperate

This commit is contained in:
JJJHolscher 2023-10-10 21:39:58 +02:00
parent afe64aaada
commit bf2c478ac8

View File

@ -1,11 +1,28 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
import inspect
import os import os
from pathlib import Path import sys
from importlib.resources import files from importlib.resources import files
from pathlib import Path
from typing import Optional
import __main__ import __main__
def walk_stack() -> Optional[Path]:
stack = inspect.stack()
i = 0
file_name = "<>"
while -i <= len(stack) and file_name[0] == "<" and file_name[-1] == ">":
i -= 1
file_name = stack[i].filename
if file_name[0] == "<" and file_name[-1] == ">":
return None
return Path(file_name)
def root_dir(): def root_dir():
if "FILE_PATH" in os.environ: if "FILE_PATH" in os.environ:
return Path(os.environ["FILE_PATH"]).parent() return Path(os.environ["FILE_PATH"]).parent()
@ -13,19 +30,22 @@ def root_dir():
if __main__.__package__: if __main__.__package__:
return files(__main__.__package__) return files(__main__.__package__)
# Use the folder of the main file as toml_dir.
if "__file__" in dir(__main__): if "__file__" in dir(__main__):
toml_dir = Path(__main__.__file__).parent return Path(__main__.__file__).parent
return toml_dir
# Find the path of the ipython notebook. # Find the path of the ipython notebook.
try: try:
get_ipython()
import ipynbname import ipynbname
return ipynbname.path().parent return ipynbname.path().parent
except IndexError: except (NameError, IndexError):
pass pass
out = walk_stack()
if out:
return out.parent
return Path(os.path.abspath(".")) return Path(os.path.abspath("."))
@ -36,14 +56,22 @@ def root_file():
if "FILE_NAME" in os.environ: if "FILE_NAME" in os.environ:
return root_dir() / os.environ["FILE_NAME"] return root_dir() / os.environ["FILE_NAME"]
if __main__.__package__:
return files(__main__.__package__).joinpath("__main__.py")
if "__file__" in dir(__main__): if "__file__" in dir(__main__):
return Path(__main__.__file__) return Path(__main__.__file__)
try: try:
get_ipython()
import ipynbname import ipynbname
return ipynbname.path() return ipynbname.path()
except IndexError: except (NameError, IndexError):
pass pass
out = walk_stack()
if out:
return out
raise NotImplementedError raise NotImplementedError