Often we have scripts that require a home folder location for the script to locate related files -- for example, layer files, data distributed with the tool that it uses, etc. Here are some methods to find that location.
os.path.dirname(sys.argv[0]) or os.path.dirname(__file__).
Both these locations find the path of the currently running Python script file.
Usually, __file__ is the best choice.
See: Difference between __file__ and sys.argv[0] (StackOverflow)
Toolbox (.tbx) validation code
In .tbx script tool validation code, sys.argv[0] returns an empty string, but __file__ will be the path to the function packed in a string like this: u'C:\\test\\Toolbox.tbx#Script_z.InitializeParameters.py'
In this case, the location of the tbx would be: os.path.dirname(__file__)
ModelBuilder tbx location
The ModelBuilder tbx location can be found using os.path.realpath and the Calculate Value tool with this code block:
<SPAN class="comment token"># Call with expression: home()</SPAN>
<SPAN class="keyword token">import</SPAN> os
<SPAN class="keyword token">def</SPAN> <SPAN class="token function">home</SPAN><SPAN class="punctuation token">(</SPAN><SPAN class="punctuation token">)</SPAN><SPAN class="punctuation token">:</SPAN>
<SPAN class="keyword token">return</SPAN> os<SPAN class="punctuation token">.</SPAN>path<SPAN class="punctuation token">.</SPAN>realpath<SPAN class="punctuation token">(</SPAN><SPAN class="string token">"."</SPAN><SPAN class="punctuation token">)</SPAN><SPAN class="line-numbers-rows"><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN></SPAN>
Map document location ("Home folder" in ArcMap or Pro)
Some script tools (always run from ArcMap or Pro) may need to locate data relative to the .mxd or .aprx location:
<SPAN class="comment token"># ArcMap</SPAN>
here <SPAN class="operator token">=</SPAN> os<SPAN class="punctuation token">.</SPAN>path<SPAN class="punctuation token">.</SPAN>dirname<SPAN class="punctuation token">(</SPAN>arcpy<SPAN class="punctuation token">.</SPAN>mapping<SPAN class="punctuation token">.</SPAN>MapDocument<SPAN class="punctuation token">(</SPAN><SPAN class="string token">"CURRENT"</SPAN><SPAN class="punctuation token">)</SPAN><SPAN class="punctuation token">.</SPAN>filePath<SPAN class="punctuation token">)</SPAN>
<SPAN class="comment token"># ArcGIS Pro</SPAN>
here <SPAN class="operator token">=</SPAN> arcpy<SPAN class="punctuation token">.</SPAN>mp<SPAN class="punctuation token">.</SPAN>ArcGISProject<SPAN class="punctuation token">(</SPAN><SPAN class="string token">"CURRENT"</SPAN><SPAN class="punctuation token">)</SPAN><SPAN class="punctuation token">.</SPAN>filePath<SPAN class="line-numbers-rows"><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN></SPAN>