Select to view content in your preferred language

Modules for Dummy

670
3
06-07-2013 10:18 AM
MaryM
by
Deactivated User
I have been diving through Python this year and have gotten stuck at modules.  I have four scripts that perform some awesome fixes for MXDs when there is a database change.  However, I have to put the same functions and variables at the top of each one of the scripts.  I was thinking of turning this into a module or package?  I cannot seem to figure these module/packages out.  My question is for Python 2.6.5/ArcGIS 10...  What would need to be in __init__.py?  How would I set up the global variables/functions for all the scripts to use?  How do I register all the scripts to be able to recognize what went on in the others?  I have tried the helps out there but am further lost.  Maybe someone can help me and then I can fix and post my product?
Tags (2)
0 Kudos
3 Replies
markdenil
Frequent Contributor
Chose or make one script for the main process.
import all the other scripts (modules) into it.

You may want to adjust the python path to make sure your modules are found
This can be done temporarily (for the session) by using
sys.path.append(customPath)
where customPath is the path to your modules.
set this before the custom module imports

set up the modules with function defs.
I like pass all the objects, modules and variables used in the function into it as arguments.
for example, in a hypothetical customModule_2:
def processTheData(arcpy, sys,
                 customModule_3,
                 customModuleToolConfig,
                 customModuleToolHelper,
                 variable1, variable2, listA):


Then invoke it like this:
return_2 = customModule_2.processTheData(arcpy, sys,
                                  customModule_3,
                                  customModuleToolConfig,
                                  customModuleToolHelper,
                                  "Whoppie!", 2013, listOfStuff)


The return can be whatever you want back:
even if it is just a boolean for sucsessful completion.

below all the def / functions in the supporting modules,
one can add something like
#       safety
if __name__ == "__main__":
    print "This script does not run alone."

so the module script won't try to the start the overall process in the middle.

As well, once the whole process is running correctly,
a .pyc file will have been generated for each imported module.
At that point you can remove those .py files from the accessable directory.
It is not perfect security, but it means no one can casually damage the script
by "just lookin' at it" in a text editor.
Leave the main script as a py, and maybe a configuration module, too, for easy modification.
0 Kudos
MaryM
by
Deactivated User
Okay, setting up the modules to run with all the objects being passed to them may help my problem.  Does anything need to be in __init__.py?
0 Kudos
markdenil
Frequent Contributor
Not likely, but it depends on what you are trying to do.
0 Kudos