How to reference a tool script when validating?

142
1
02-21-2019 11:14 AM
JonathanBailey
Occasional Contributor III

I've defined a simple Python script to download a file:

import arcpy
import requests
import os
import urllib

def download_file(url):
 output_file_name = get_output_file_name(url)

 with open(output_file_name, 'wb') as output_file:
 response = requests.get(url)
 output_file.write(response.content)
 
 arcpy.SetParameterAsText(1, output_file_name)

def get_output_file_name(url):
 path = urllib.parse.urlparse(url).path
 base_file_name = os.path.basename(path)
 scratch_folder = arcpy.env.scratchFolder
 return os.path.join(scratch_folder, base_file_name)

if __name__ == "__main__":
 url = arcpy.GetParameterAsText(0)
 download_file(url)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

and, I've created a script tool in a custom toolbox with an input parameter (the url of the file to download) and an output parameter (the path to the downloaded file).

To validate the tool, I need to set the value of the output parameter. I have a method for this in my script (get_output_file_name). How can I call this from within my Tool Validator code in the custom toolbox?

0 Kudos
1 Reply
RandyBurton
MVP Regular Contributor

Untested, but perhaps something like:

import arcpy
import requests
import os
import urllib

class ToolValidator:

    def __init__(self):
        self.params = arcpy.GetParameterInfo()

    def initializeParameters(self):
        # (initializeParameters code here)
        return

    def updateParameters(self):
        if self.params[0].altered:
            if self.params[0].value: # a url has been entered in first parameter
                url = self.params[0].value
                path = urllib.parse.urlparse(url).path
                base_file_name = os.path.basename(path)
                scratch_folder = arcpy.env.scratchFolder
                self.params[1].value = os.path.join(scratch_folder, base_file_name)
        return

    def updateMessages(self):
        # (updateMessages code here)
        return‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Then use:  output_file_name = arcpy.GetParameterAsText(1).

0 Kudos