Skip to content
Advertisement

Accessing script file location from an external file python

I have the following bizarre set up. Consider 3 scripts in different directories:

  • root1/folderA/scriptA.py
  • root2/folderB/scriptB.py
  • root2/folderC/scriptC.py

The first file and it’s location are fully modifiable. The second and third are completely fixed.

scriptA.py contains a parent class:

JavaScript

scriptB.py contains a child class:

JavaScript

scriptC.py contains the code to execute:

JavaScript

In scriptC.py what I want is the behaviour to get the path of the child class’s declaration file (without any hard-coding). Is there any way to program the A.get_path() to have this behavoir?

I’ve tried looking into the inspect, os.path and pathlib modules but I haven’t had any luck.

Advertisement

Answer

It looks like the trick is to use __init_subclass__ which runs whenever a class is sub-classed, in conjunction with a class’s __module__ attribute to retrieve its containing module, and __file__ to retrieve the absolute path to the python script or module.

For example, in script_a.py:

JavaScript

script_b.py:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement