How to implement os.getcwd() in Pro 2.1.2?

1897
12
Jump to solution
06-04-2018 01:18 PM
ThomasColson
MVP Frequent Contributor

When attaching the following to a tool box in Pro 2.1.2 and running it: 

import os
import errno
import arcpy
curr = dirpath = os.getcwd()
directories = ['Data','Data//GPS','Data//Working','Data//Tabular','Products','Documents', 'Documents//Pics_Graphics']
basedirectory = curr +'//'
for i in range (len (directories)):
 newDir = basedirectory + directories[i]
 try:
 os.makedirs(newDir)
 except OSError as exception:
 if exception.errno != errno.EEXIST:
 raise
 else:
 print ("\nBE CAREFUL! Directory %s already exists." % newDir)

I get the following error: 

Start Time: Monday, June 04, 2018 4:10:17 PM
Running script CreateProjectFolders...
Failed script Create Project Folders...
 Traceback (most recent call last):
 File "C:\temp\Pro_Folder_Structure\NEW_FOLDERS.py", line 10, in <module>
 os.makedirs(newDir)
 File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\os.py", line 220, in makedirs
 mkdir(name, mode)
PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\ArcGIS\\Pro//Data'
 Failed to execute (CreateProjectFolders).
Failed at Monday, June 04, 2018 4:10:17 PM (Elapsed Time: 0.06 seconds)

My assumption is that os.getcwd() would get the directory that the pro project is saved to. curr = dirpath = arcpy.env.workspace doesn't appear to do anything here. 

0 Kudos
1 Solution

Accepted Solutions
DanPatterson_Retired
MVP Emeritus
aprx ='C:\\Users\\sasquatch\\Documents\\ArcGIS\\Projects\\MyProject95\\MyProject95.aprx'
folder = "/".join(aprx.split("\\")[:-1])
folderOut[17]: 'C:/Users/sasquatch/Documents/ArcGIS/Projects/MyProject95'

View solution in original post

12 Replies
DanPatterson_Retired
MVP Emeritus

Well the first bit works

import os

curdir = os.getcwd()

curdir
'C:\\GIS\\A_Tools_scripts\\Table_tools\\Scripts'

But your indentation is all wrong, if you copied and pasted your code.

I suggest that you fix it with 4 space indentation AND

If you intend to use forward slashes, you only use 1 ie '/'

Backslashes use 2 ie '\\'

Throw in some print statements as you go along to see where failure actually occurs.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

If you copy the following into a file and run it as a script associated with a Toolbox, what path is returned:

import os
import arcpy

arcpy.AddMessage("----------------------------------------")
arcpy.AddMessage(os.getcwd())
arcpy.AddMessage("----------------------------------------")
0 Kudos
ThomasColson
MVP Frequent Contributor

The problem is not the indentation or the spaces, the problem is, when run from within a Pro toolbox, or the Pro Python window, 

arcpy.AddMessage(os.getcwd()) 

returns C:\Program Files\ArcGIS\Pro. It does not return the path to the Pro Project Folder. 

The script runs fine as a stand alone, and creates the folders in what ever folder the script happens to be in. The home folder property in ArcGISProject—ArcPy | ArcGIS Desktop seemed promising, but all that returns is <property object at 0x000000017836EF98> and arcpy.mp.ArcGISProject("CURRENT").filePath returns the full path as well as the name of the aprx, which I don't need (and therefore can't use the output of arcpy.mp.ArcGISProject("CURRENT").filePath either). 

0 Kudos
DanPatterson_Retired
MVP Emeritus

One useful way that doesn't require arcpy at all in case you work outside of arcmap is to organize your projects so that you have your scripts in a subfolder within the folder.

You just need to find out where the script is, then parse the path to the project

import sys  # assuming you don't already have it
script = sys.argv[0]
script'C:/GIS/A_Tools_scripts/Table_tools/Scripts/sequential_funcs_txt.py'
proj = "/".join(script.split("/")[:-2])
proj 'C:/GIS/A_Tools_scripts/Table_tools'  # the project folder, which contains the *.aprx and the *.tbx‍‍‍‍‍‍‍‍‍‍

The trouble with the ArcGISProject is that it only returns useful information if you are running the python script in the sad python window or from the application

activeMap
(Read Only)

Returns the map object associated with the focused view within the application.None will be returned if there are no views open that have an associated map or when a script is run outside of the application.

And in any event you would have to provide "CURRENT" I suppose to 

ArcGISProject("CURRENT") to the method... but it returns too many 'None' if as described in the help (ie no active map etc)

0 Kudos
ThomasColson
MVP Frequent Contributor

That would work if there were either a fixed location of the script, or a fixed location where all projects get saved, and users were inclined to provide input to sys.argv[0], and if they were so inclined, we'd start seeing

['Data','Data//GPS','Data//Working','Data//Tabular','Products','Documents', 'Documents//Pics_Graphics']

all over the network, anywhere in fact, instead of in the prj folder. Another limitation is we have an enforced policy on project folder organization, adding more subfolders with scripts is not in the cards. Trying to make this a hands off solution, Start Pro, click a button, there are your folders. In Arc I do this with a zip/exe which has been identified as a "security concern". What I'm really interested in is corralling the output of arcpy.mp.ArcGISProject("CURRENT").filePath to NOT give me 'C:\\Users\\sasquatch\\Documents\\ArcGIS\\Projects\\MyProject95\\MyProject95.aprx'  but instead 'C:\\Users\\sasquatch\\Documents\\ArcGIS\\Projects\\MyProject95\\' 

So, in Pro 2.1.2, is it possible to simply get the path of the current project using Python? Not the path to "Program Files" or the name of the project.....

DanPatterson_Retired
MVP Emeritus
aprx ='C:\\Users\\sasquatch\\Documents\\ArcGIS\\Projects\\MyProject95\\MyProject95.aprx'
folder = "/".join(aprx.split("\\")[:-1])
folderOut[17]: 'C:/Users/sasquatch/Documents/ArcGIS/Projects/MyProject95'
ThomasColson
MVP Frequent Contributor

Marked correct. But back to your original idea, how WOULD you give the user a choice? Run the tool with no input and get the folders in the project directory, OR, specify an existing folder in the project directory or create a new one, and put the folders there. 

import os
import errno
import arcpy
curr = arcpy.mp.ArcGISProject("CURRENT").filePath
folder = "/".join(curr.split("\\")[:-1])
directories = ['Data','Data\\GPS','Data\\Working','Data\\Tabular','Products','Documents', 'Documents\\Pics_Graphics']
basedirectory = folder +'\\'
for i in range (len (directories)):
 newDir = basedirectory + directories[i]
 try:
 os.makedirs(newDir)
 except OSError as exception:
 if exception.errno != errno.EEXIST:
 raise
 else:
 print ("\nBE CAREFUL! Directory %s already exists." % newDir)
0 Kudos
DanPatterson_Retired
MVP Emeritus

Depends on the level of familiarity with GIS that you users have.

  1. None... then they need some guidance and a pre-created structure.
  2. Some... prefabricate some folders in a master folder and get them to copy into the PRO project folder.

We don't use a master folders for toolboxes and/or scripts. 

User developed toolboxes and scripts are copied into each project folder as needed.  Why? it is simple, disk space is

cheap and people can handle the "copy here, use here, backup there" pretty well.

So in short if someone wants to use something (regardless of whether it is tools or scripts or data, they copy it locally.

Of course, those that are required to have stuff on a central repository have to deal with those issues.  We just find the

work local, backup elsewhere works fine but... we don't have people tripping over themselves trying to use/update the same data at the same time.  That is an extra level of issues that fortunately we don't have to deal with.

BTW that doesn't apply just to teaching but to consulting work as well.

Best of luck

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Interesting.  When I run the code from a script in a Toolbox, it gives me the path to the current project and not Pro's install folder.  I realize you have found a solution, or usable workaround, but I still wonder why you are getting different results than I am with same version of Pro.  Is the Toolbox part of the project's Toolbox folder or connected/mapped to from a central location or file share?