This post shows how to call a script from a script in Python. See the discussion and alternatives
http://forums.arcgis.com/threads/27090-How-do-you-call-a-Script-from-a-Script
If the script is run in standalone mode, it will perform three operations and return results. This script could be imported into other scripts and you could draw from / call any of the functions within and return their results.
So here is an example of some functions and an example of what would result if run in standalone mode.
'''
Callingfunctions.py
imported into another program giving it access to the functions
For example
#somescript.py
import Callingfunctions as CF
print "sum of a bunch of numbers, sumData([1,2,3,4,5,6,7,8,9,10]) )
'''
def sumData(inputs=None):
x = sum(inputs)
return "sum some numbers: ", x
def sumSquares(inputs=None): #summing squares of numbers
x_sq = 0
for x in inputs:
x_sq += x**2
return "sum of squares: ", x_sq
def sayHello(inputs=None): #another classic
return "hello from Python: ", inputs
#---------------------------------------------------------------
#if run in standalone mode
if __name__ == "__main__":
a_list = [1,2,3,4,5,6,7,8,9,10]
inputs = "test inputs"
a_dict = {1:sumData([1,2,3]),
2:sumSquares([1,2,3]),
3:sayHello("inputs to sayhello ")}
needed = [1,2,3]
for akey in needed:
if akey in a_list:
action = a_dict[akey]
print action
If you want to use a main program to run the example rather than run the above in standalone mode, you simply have to call the script and use it. It is imperative that both programs reside in the same folder. Here is an example "main" script
'''
Main_program.py
demonstrates how to import and call functions from another module
'''
import sys
import CallingFunctions
a_list = [1,2,3,4,5,6,7,8,9,10]
print sys.argv[0]
print CallingFunctions.func1(a_list)
print CallingFunctions.func2(a_list)
print CallingFunctions.func3(a_list)
No comments:
Post a Comment