Select to view content in your preferred language

Get script path from ToolValidator

683
3
04-12-2014 06:59 AM
LT
by
Regular Contributor
Hi All,

From inside the ToolValidator in a script tool, is there a way to determine the path of the script to which a script tool is pointing? 

I'd like to set the default value of an input data file based on its relative path to the script.   An acceptable alternative for me would be to detect the location of the toolbox containing the script tool.  But the following return empty strings inside the ToolValidator class:

os.getcwd
sys.argv[0]
os.path.abspath(__file__)
inspect.getfile(inspect.currentframe())


Thanks!
Tags (2)
0 Kudos
3 Replies
MattEiben
Deactivated User
It looks like you were super close!
If you're looking to get the relative path to the script the Validator Tool is pointing towards, try this:

file_path = os.path.dirname(os.path.abspath(__file__))


If you're looking to concatenate that with something else, then you could use os.path.join like this:

file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), NameOfOtherDataRelativeToYourScript)


Hope this helps!

Matt
0 Kudos
LT
by
Regular Contributor
Thanks Matt! 

I don't know why os.path.abspath(__file__) gave me an empty string before.  (Probably the lag time between each edit of the ToolValidator is doing my head in!)

In fact, it gives something like this:
'path to toolbox\toolboxName.tbx#scriptToolName.UpdateMessages.py'

I can take it from there...
0 Kudos
by Anonymous User
Not applicable
Since the current working directory will be temporarily appended to your PYTHONPATH as the first or second item (depending on if it inserts a blank '' path), this also works:

import sys
cur = filter(None, sys.path)[0]


I think it only inserts the '' as the first item when you are using the shell window, but using the filter *should* be fail safe.  I should also add this will only work if embedded in your script, not the shell window.
0 Kudos