I'm trying to call a function defined in a script contained in Toolbox. I have imported the Toolbox via arcpy.ImportToolbox. The scripts contained are recognized. I cannot call the function defined to each one.
Why are you calling a script in your toolbox? and from where?
Are you not using the toolbox inside of arcmap or ArcGIS pro?
Is it a python toolbox or a conventional toolbox?
Adding toolboxes in Python—Geoprocessing and Python | ArcGIS Desktop
Have you imported your toolbox first?
In the following example, the ImportToolbox function is used to allow tools contained in a custom toolbox to be accessed in Python. After importing the toolbox, the custom tools can be accessed as arcpy.<toolname>_<alias>.
>>> arcpy.ImportToolbox("c:/mytools/geometrytools.tbx") >>> arcpy.CreateRegularPolygons_geometry(
You might want to elaborate on your situation more
I have added a Toolbox named "Test", in which 4 password-protected scripts are imported. Script script2 (imported in the Toolbox "Test") with user-defined parameters is used to call the other ones (depending on the defined parameters). In the scripts I have defined functions. e.g. script1.py
def PhiLamdah2XYZ(Phi, Lamda, h, a, f):
...
return(X,Y,Z)
def XYZ2PhiLamdah(X, Y, Z, a, f):
...
return(GeodCoord_Dall)
Script Script2.py imports the Toolbox "Test":
relPath = os.path.dirname(__file__)
PythonTBX = relPath + r"\Test.tbx"
arcpy.ImportToolbox(PythonTBX)
Is there a way to call the functions PhiLamdah2XYZ and XYZ2PhiLamdah from Script2.py?
If the scripts are in the same location as the other scripts, why don't you just import those
ie.
Script1 is your main script (module) and script 2 is in the same location
Add this line
from script2 import PhiLamdah2XYZ, XYZ2PhiLamdah
script1.py
# -*- coding: utf-8 -*-
"""
script1.py
"""
from script2 import hello
name = hello(nme=None) # nme='Bob'
print(name)
script2.py
# -*- coding: utf-8 -*-
"""
script2.py
"""
def hello(nme=None):
if nme is None:
nme = "Hello You"
else:
nme = "Hello {}! ".format(nme)
nme += " called from script2"
return nme
Run script1, you can change line 6 in script 1 to test
runfile('C:/Temp/script1.py', wdir='C:/Temp')
Reloaded modules: script2
Hello You called from script2
# ---- changed input to script 1
runfile('C:/Temp/script1.py', wdir='C:/Temp')
Reloaded modules: script2
Hello Bob! called from script2
The problem arises when I import the scripts in the Toolbox.
error messages?
is this a python toolbox (pyt)
I guess you are going to have to show what you have, since you appear to be doing something different than normal imports support
try the toolbox alias approach