Ibe
Ibe

Reputation: 6035

How to declare folder name as global

Following code shows first step where i have to declare output folder as global so that later outputs can be saved in it as well. Right now I am getting an error at output folder string r'optfile/ras1'. Any help how to correctly store files in output folder and declare it as global would be appreciative.

import arcpy
import os
import pythonaddins

from datetime import datetime

now = datetime.now()
month = now.month
year = now.year

optfile = "C:/temp/"+str(year)+"_"+str(month)

class DrawRectangle(object):
"""Implementation for rectangle_addin.tool (Tool)"""
    def __init__(self):
        self.enabled = True
        self.cursor = 1
        self.shape = 'Rectangle'
        os.makedirs(optfile)        

    def onRectangle(self, rectangle_geometry):
    """Occurs when the rectangle is drawn and the mouse button is released.
        The rectangle is a extent object."""

        extent = rectangle_geometry
        arcpy.Clip_management(r'D:/test', "%f %f %f %f" %(extent.XMin, extent.YMin, extent.XMax, extent.YMax), r'optfile/ras1', "#", "#", "NONE")
        arcpy.RefreshActiveView()

Upvotes: 0

Views: 1906

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121406

I think you mean that the value r'optfile/ras1' doesn't use your optfile variable. That's because Python does not magically read your mind and replace parts of strings that happen to match a variable name.

You have to use the optfile variable explicitly, by concatenating it with the /ras1 part:

    arcpy.Clip_management(
        r'D:/test',
        "%f %f %f %f" %(extent.XMin, extent.YMin, extent.XMax, extent.YMax),
        optfile + '/ras1', "#", "#", "NONE")

or, better yet, use the os.path.join() function to take care of the path separators for you:

import os.path

# ...

    arcpy.Clip_management(
        r'D:/test',
        "%f %f %f %f" %(extent.XMin, extent.YMin, extent.XMax, extent.YMax),
        os.path.join(optfile, 'ras1'), "#", "#", "NONE")

Note that your problem has nothing to do with global variables; this applies to wherever your variable that you want to concatenate comes from.

Upvotes: 1

Related Questions