Select to view content in your preferred language

Geoprocessing service to return a file

4882
10
Jump to solution
07-21-2020 01:50 AM
VictorTey
Esri Contributor

Hi,

How can I get a geoprocessing service to return a file?

I published a GP

if __name__ == '__main__':

    file = open(arcpy.env.scratchWorkspace+ "/" + "test.txt","w")
    file.write("why")
    file.close()
    arcpy.SetParameter(0, file.name)‍‍‍‍‍‍‍‍‍‍‍‍

':

however i kept receiving the 

 "value": "d:\\arcgisserver\\directories\\arcgisjobs\\script_gpserver\\j94a7e5b06f3342deb0ebcb65467f63fe\\scratch/test.txt"

I can see the file in the scratch folder but i need to return the file some how.

I did try to access the file via different permutation of 

https://example.com/arcgis/rest/services/Script/GPServer/Script/jobs/j94a7e5b06f3342deb0ebcb65467f63... to no avail

Can someone kindly assist.

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
BruceHarold
Esri Regular Contributor

Victor, the team here notice your output data type is GPString, please change it to GPFile. it should then work.

View solution in original post

10 Replies
Egge-Jan_Pollé
MVP Regular Contributor

Hi Victor Tey,

Why do you put a forward slash between the path and the file?

What happens if you replace this "/" with "\\"?

Does this solve your issue?

BR,

Egge-Jan

VictorTey
Esri Contributor

I had rewritten the code several times

txtFile = os.path.join(arcpy.env.scratchFolder, "myTxt.txt")
f = open(txtFile, 'w')
f.writelines("huh")
f.close
arcpy.SetParameterAsText(0, txtFile)

One of them is as shown above, still the same .

I have arcgis enterprise installed locally, would that have made a difference?

0 Kudos
DanPatterson
MVP Esteemed Contributor
j94a7e5b06f3342deb0ebcb65467f63fe

This number differs from the one in the your image... is that supposed to happen?


... sort of retired...
VictorTey
Esri Contributor

My apologies, I had so many tabs opened and I must have copy and paste from the wrong tab

txtFile = os.path.join(arcpy.env.scratchFolder, "myTxt.txt")
    f = open(txtFile, 'w')
    f.writelines("huh")
    f.close
    arcpy.SetParameterAsText(0, txtFile)‍‍‍‍‍
0 Kudos
BruceHarold
Esri Regular Contributor

Victor, the team here notice your output data type is GPString, please change it to GPFile. it should then work.

VictorTey
Esri Contributor

Spot on, thank you so much , this is my first attempt working with publishing GP and trying to piece together how everything works together

BruceHarold
Esri Regular Contributor

Superseded by my comment above but still useful!  To answer your original question, to return your output file parameter (in Pro) wrap the web tool in a model and add the Copy geoprocessing tool to copy it into your project.  The file has to be a supported type.  Here is an example where the web tool is a Spatial ETL tool which I featured in my recent UC technical workshop on Data Interoperability extension.  The experience of a web tool output going to a rather obscure profile directory is under review by geoprocessing team.  Note:  The intermediate scratchfile will be deleted when you exit Pro, this is also under review.

VictorTey
Esri Contributor

Thank you all for your help. It turns out I have been really silly.

I kept attempting to access the file via  "arcgis/rest/services/

arcgis/rest/services/Script5/GPServer/Script/jobs/j24670b8fb4944b60993fa840472bc2f8/results/URL

where else the output of the directory is actually on arcgis/rest/directories/arcgisjobs

arcgis/rest/directories/arcgisjobs/script5_gpserver/j05515f60833c4e15a8d461f40acb1484

0 Kudos
Marc_Alx
Emerging Contributor

For further reader, here's a sample geoprocessing toolbox with a tool that returns a file.

Some notes

- Your parameter file must have a "direction" of "Output" and a "parameterType" of "Derived"

- The file type for geoprocessing parameter is "DEFile", for some reason "GPDataFile" results in no file being accessible to end user. Once published it appears as "GPDatafile"

- Result must be set via arcpy.setParameterAsText whereas setting "value" of a saved parameter does nothing.

- In order to be accessible you file must be wrote/saved to "arcpy.env.scratchFolder". Arcpy rewrite this path once published to an accessible URL.

- If you wish to backup your file outside of "arcpy.env.scratchFolder" you have to register the save location, from ArcGIS Pro: add any folder you need via: Share→Manage→Data stores, here add a new `folder` with `Publish folder path` set to the path you want to expose. Keep in mind that any hard coded path will be consolidated (to a sandbox path) on publish by ArcGIS.

 Some useful links

Authoring web tools with Python scripts (to understand path consolidation)

- Publish web tool

The code

# -*- coding: utf-8 -*-

import arcpy
from os.path import join

class Toolbox(object):
    def __init__(self):
        """Sample file toolbox"""
        self.label = "Sample file toolbox"
        self.alias = "File toolbox"

        # List of tool classes associated with this toolbox
        self.tools = [GetFileTool]

class GetFileTool(object):

    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Get file tool"
        self.description = "A tool to get a file"
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""
        return [arcpy.Parameter(displayName="Output_File",
                                name='Output_File',
                                datatype=['DEFile'],
                                parameterType='Derived',
                                direction='Output')]

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return
    
    def exitWithError(self,msg):
        """
            exit geoprocessing with a given error msg
            under the hood it raise an exception, msg is logged as error
        """
        raise ValueError(msg)

    def execute(self, parameters, messages):
        """The source code of the tool."""
        p = join(arcpy.env.scratchFolder, "test.txt")
        with open(p, 'w') as f:
            f.write('hello')
        #set result with SetParameterAsText, setting result via 'value' parameter of objects inside parameters does nothing
        arcpy.SetParameterAsText(0,p)