Commits

Jason Scheirer  committed d8ee9e5

Create a .pyt to implement underlying functionality

  • Participants
  • Parent commits 52a7264

Comments (0)

Files changed (2)

File converttbx.pyt

+# -*- coding: utf-8 -*-
+
+import contextlib
+import os
+import sys
+
+import arcpy
+
+@contextlib.contextmanager
+def script_run_as(filename, args=None):
+    oldpath = sys.path[:]
+    oldargv = sys.argv[:]
+    newdir = os.path.dirname(filename)
+    sys.path = oldpath + [newdir]
+    sys.argv = [filename] + [arg.valueAsText for arg in (args or [])]
+    oldcwd = os.getcwdu()
+    os.chdir(newdir)
+
+    try:
+        # Actually run
+        yield filename
+    finally:
+        # Restore old settings
+        sys.path = oldpath
+        sys.argv = oldargv
+        os.chdir(oldcwd)
+
+class Toolbox(object):
+    def __init__(self):
+        self.label = u'Convert to PYT'
+        self.alias = u'pytmaker'
+        self.tools = [CreatePYT]
+
+# Tool implementation code
+
+class CreatePYT(object):
+    def __init__(self):
+        self.label = u'Create PYT Template from TBX'
+        self.description = u'Create a new PYT skeleton from the structure and parameters of an ArcGIS Toolbox (TBX) file.'
+        self.canRunInBackground = False
+    def getParameterInfo(self):
+        # Input_Toolbox
+        param_1 = arcpy.Parameter()
+        param_1.name = u'Input_Toolbox'
+        param_1.displayName = u'Input Toolbox'
+        param_1.dataType = u'Toolbox'
+        param_1.parameterType = 'Required'
+
+        # Output_File
+        param_2 = arcpy.Parameter()
+        param_2.name = u'Output_File'
+        param_2.displayName = u'Output File'
+        param_2.dataType = u'File'
+        param_2.parameterType = 'Required'
+
+        return [param_1, param_2]
+    def isLicensed(self):
+        return True
+    def updateParameters(self, parameters):
+        pass
+    def updateMessages(self, parameters):
+        pass
+    def execute(self, parameters, messages):
+        with script_run_as(__file__):
+            import tbxtopyt
+            if not parameters[1].valueAsText.lower().endswith('.pyt'):
+                parameters[1].value = parameters[1].valueAsText + ".pyt"
+            tbxtopyt.export_tbx_to_pyt(parameters[0].valueAsText, parameters[1].valueAsText)
 pytexportutils = imp.load_module('pytexportutils', *mod_find)
 
 ACCEPTABLE_VARIABLENAME = re.compile("^[_a-z][_a-z0-9]*$", re.IGNORECASE)
+CALL_RE_TEMPLATE = "((?:[_a-z][_a-z0-9]* *[.] *)*{}\(([^)]*)\))"
 CODING_RE = re.compile("coding: ([^ ]+)")
 HEADER_SOURCE = """# -*- coding: utf-8 -*-
 
 # You can ignore/delete this code; these are basic utility functions to
 # streamline porting
 
-@contextlib.contextmanager:
-def fakefile(filename, args=None):
+@contextlib.contextmanager
+def script_run_as(filename, args=None):
     oldpath = sys.path[:]
     oldargv = sys.argv[:]
     newdir = os.path.dirname(filename)
     sys.path = oldpath + [newdir]
-    sys.argv = [filename] + map(get_value_as_text, args or [])
+    sys.argv = [filename] + [arg.valueAsText for arg in (args or [])]
     oldcwd = os.getcwdu()
     os.chdir(newdir)
 
         sys.argv = oldargv
         os.chdir(oldcwd)
 
-def get_parameter_as_text(parameter_object):
-    val = parameter_object.value
-    val = getattr(val, 'value', val)
-    if not isinstance(val, basestring):
-        val = str(val)
-    return val
-
 def set_parameter_as_text(params, index, val):
     params[index].value = val
 """
     ('GetArgumentCount', 'len(parameters)')
 )
 
-CALL_RE_TEMPLATE = "((?:[_a-z][_a-z0-9]* *[.] *)*{}\(([^)]*)\))"
-
 def collect_lines(fn):
     def fn_(*args, **kws):
         return '\n'.join(fn(*args, **kws))
     src = "\n".join("{}{}".format(" " * indentation,
                                   line.encode("utf-8"))
                                   for line in source.split("\n"))
-    # Now apply some super mechanical translations to common parameter access routines
+    # Now apply some mechanical translations to common parameter access routines
     for fnname, replacement_pattern in FUNCTION_REMAPPINGS:
         regexp = re.compile(CALL_RE_TEMPLATE.format(fnname))
         finds = regexp.findall(src)
             filename = pytexportutils.IGPScriptTool(self._tool).FileName
             if os.path.isfile(filename):
                 file_contents = open(filename, 'rb').read()
-                yield "        with fakefile({}):".format(repr(filename))
+                yield "        with script_run_as({}):".format(repr(filename))
                 yield rearrange_source(file_contents, 12)
             else:
                 yield "        # {}".format(repr(filename))
                 try:
                     # Coerce as source?
                     compile(filename, self._tool.PathName, "exec")
-                    yield "        with fakefile({}):".format(repr(self._tool.PathName))
+                    yield "        with script_run_as({}):".format(repr(self._tool.PathName))
                     yield rearrange_source(filename, 12)
                 except:
                     pass