Can I access global variables in called python?

1387
0
02-08-2017 08:13 AM
MarkWingfield
New Contributor III

Trick one to explain but I will give it a go with simplified code.

I originally had a python script that had some global variables defined at the top, some functions and then the main code in a "try" statement. eg

PythonScript.py

import arcpy, os, sys

arcpy.env.workspace = arcpy.GetParameterAsText(0)
LogAllEvents = arcpy.GetParameterAsText(1)

globalVariable1 = "Global1"

globalVariable2 = "Global2"

sdeConn = arcpy.ArcSDESQLExecute(arcpy.env.workspace)

def somefunc(Global1):

   print Global1

def someotherfunc(Global2)

   global Global1

   print Global2

   Global1 = Global2

try:

   print "Starting Process"

   somefunc(Global1)

   someotherfunc(Global2)

   #now carry out some logic using sdeconn

I now have realized I need a method of calling this python script to perform the main functionality, so have altered this as follows:

PythonScript.py

import arcpy, os, sys

def somefunc(Global1):

   print Global1

def someotherfunc(Global2)

   global Global1

   print Global2

   Global1 = Global2

def main(arcpy.env.workspace, LogAllEvents )

   print "Starting Process"

   globalVariable1 = "Global1"

   globalVariable2 = "Global2"

   sdeConn = arcpy.ArcSDESQLExecute(arcpy.env.workspace)

   somefunc(Global1)

   someotherfunc(Global2)

   #now carry out some logic using sdeconn

if __name__ == "__main__":

   main(dummy,dummy)

I will always call the main() from another python script so please ignore the details of the "if __name__" statement above. My call from the other script will be:

OtherScript.py

import arcpy, os, sys, PythonScript

arcpy.env.workspace = arcpy.GetParameterAsText(0)

LogAllEvents = "Y"

PythonScript.main(arcpy.env.workspace, LogAllEvents)

As you can see, in PythonScript, I moved all global variables into the function main().

I had to do this as it was a function that I would be calling directly from another script. Could I have left these at the top of the script and accessed in main() by defining them as global? I understand these are accessible when it is the default body of code being called but was not sure calling a function from another script.

I have simplified my scripts above. In real life there are dozens of globals and I need to get my head around this before I start shifting variables wholesale into main().

0 Kudos
0 Replies