Scripting arcgis with python

Scripting with ArcGIS API for Python

ArcGIS API for Python allows you to automate common tasks, such as creating and managing users and groups, publishing and updating items, monitoring server usage, performing visualization and data analysis, and transferring ownership of items. It also allows you to script complex tasks such as cloning portal content.

In addition to batch processing scripts, the API can be used in a browser-based interactive scripting environment called Jupyter Notebook . The notebook environment provides an interface to execute code; visualize portal items, users, and groups; and view web layers, maps, and scenes interactively.

Esri offers a Jupyter Notebook environment built in to ArcGIS Enterprise . Introduced at 10.7, ArcGIS Notebooks is hosted by ArcGIS Notebook Server , which uses containers to isolate each notebook user’s workspace. With ArcGIS Notebooks , you can use ArcGIS API for Python and ArcPy to work with the items in your portal, perform advanced spatial analysis, and craft data science workflows.

The API is built as modules that make it straightforward to learn and use. The gis module is the entry point and provides an information model to access and program your portal. The gis module provides various classes that you can use to create and manage users and their groups and items. The features and raster modules allow access to feature and raster layers, as well as the ability to perform analysis on these layers. The geoanalytics module allows the execution of GeoAnalytics Tools . To learn more about the rest of the modules and the architecture of the API, see the API overview.

Get started

The API is distributed as a Python package and can be installed using conda, which is a popular Python package and environment management system. The instructions for setup are documented on the ArcGIS Developer site.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Tutorial for how to get started scripting with python and arcpy

mwibbenmeyer/scripting_with_arcgis_using_arcpy

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Python pip ini windows

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Scripting with ArcGIS and Python using Arcpy

This is a brief tutorial for how to get started scripting ArcGIS commands in Python using Arcpy. Arcpy is a proprietary Python module that allows ArcGIS toolbox commands to be implemented through simple Python commands. There are many advantages to using arcpy , rather than manually executing commands in ArcMap or using ArcMap’s Model Builder. Unlike manually executing toolbox commands in ArcMap, scripting in Python provides a record of your work, which you can return to to edit or check your work. Model Builder also provides a record of your work; however, it comes with some disadvantages. Writing iterative loops in Model Builder is confusing, and it is not possible to write multiple nested loops. Python code is ideal for simply executing repeated commands using loops or, even better, parallelized operations across multiple computer cores. Finally, my experience is that ArcGIS commands executed using Python codes run much faster, and throw mysterious error messages far less often.

A disadvantage of running ArcGIS using Python and arcpy is that is can be a little tricky to set up. This tutorial will go through the steps to set up your machine to run Python scripts that can successfully lauch the proprietary arcpy module and any other Python modules that may be useful in your scripts.

  1. ArcGIS must be installed on your computer. This tutorial will assume that you have ArcGIS 10.3.1 installed on your computer, but the tutorial should apply to other versions of ArcGIS as well.
  2. That’s it! You don’t need to download Python, since every installation of ArcGIS 10.3.1 already comes with an installation of Python 2.7. Confirm that ArcGIS 10.3.1 (or whatever version you’re using) has installed Python to the folder C:\Python27\ArcGIS10.3\ by confirming this folder exists, and that python.exe exists within it. If you are using a different version of ArcGIS, or if ArcGIS installed Python to a different folder, you may need to modify the instructions below to fit your directory.

You may have another copy of Python already installed on your computer, and this could create issues when you launch Python and attempt to import the arcpy module. In the tutorial, I’ll explain what you should do to make sure that your computer is launching the ArcGIS installation of Python, rather than the previously installed version, so that you can successfully import the arcpy module.

Launching the ArcGIS Python installation from the command line

We want to be able to run Python scripts that call in the arcpy module. Because arcpy is a proprietary Python module, it cannot just be downloaded from the internet and installed on your computer, and it will not run with any installation of Python. It will only run with the installation of Python you received with your installation of ArcGIS (10.3.1 in my case). Therefore, we need to show the computer where it can find this installation of ArcGIS, and make sure that it finds this installation before it finds any of the other Python installations you may have on your computer.

Читайте также:  Call method java array

On your Windows 7 computer, navigate to Control Panel>System and Security>System>Advanced System settings . Once you open the System Properties window, select the «Environment Variables» button. If you have administrative privileges on your computer, select the variable «Path» under System variables. If you do not have administrative privileges on your computer, select the variable «PATH» under User variables. Without deleting directories currently found in the «Path» (or «PATH») variables, add the following directory to your path, separating it from other directories by a semicolon:

The Path variable provides a list of directories your computer will look in when you type a command in the command window. Now that you have added the location of ArcGIS’s Python installation to your path, your computer will be able to find that installation when you attempt to launch Python in the Command Prompt window, or when you execute Python scripts.

To confirm this, open up your Command Prompt window and type python . After a moment, the Python interpreter should load in your command prompt window. Once it has loaded, type import arcpy and hit enter. After several seconds (arcpy is a fairly large module, so it takes a few seconds to load), Python will prompt you to enter another command, and your command prompt window should look like this:

alt text

If that works, you’re ready to start implementing ArcGIS toolbox commands using Python scripts! If you successfully loaded Python, but you received an error message after you typed import arcpy , the problem is likely that you have another installation of Python on your computer in addition to the installation provided by ArcGIS. So when you launch Python, your computer is launching the previously installed version, rather than the version provided with ArcGIS, which is capable of importing the arcpy module. To correct this, examine your path variable for another Python directory. If another Python directory is listed in your path, your computer is likely finding python.exe within that directory before it gets around to searching C:\Python27\ArcGIS10.3 , and so it is loading the wrong installation of Python. To correct this, either delete the old Python directory from your path, or place it at the end of the list, after C:\Python27\ArcGIS10.3 .

Using arcpy with other Python modules

To make full use of arcpy and Python, you may want to use one of the many existing user-written Python modules in your Python scripts. pip is a command line program that is capable of installing Python modules from the internet. Navigate here(https://pip.pypa.io/en/stable/installing/) and download get-pip.py , a script for installing pip, to C:/Users/username/Downloads/ . Open the command prompt window and type cd C:\Python27\ArcGIS10.3\ . Then execute the following command:

python C:/Users/username/Downloads/get-pip.py 

The script will run and will install pip within your ArcGIS Python folder structure. To confirm this, use Windows Explorer to navigate to C:\Python27\ArcGIS10.3\Scripts\ . You should find a variety of newly installed applications, including pip, wheel, and easy_install.

Читайте также:  Gui python tkinter калькулятор

Last, before using pip, you need to make sure your computer knows where it is. As we did before, we need to edit the path. Navigate to Control Panel>System and Security>System>Advanced System settings , click on «Environment variables», and add C:\Python27\ArcGIS10.3\Scripts; to your System «Path» variable or your User «PATH» variable, depending your level of administrative privileges.

Now, try installing a user-written module using pip. Try installing pandas, a popular data analysis module. Click «Okay» within the Environment Variables window, open a new Windows command prompt window, and type:

If you are installing the package on your personal machine, you will (hopefully) receive a message that says that you have successfully installed pandas. If you are using a shared machine, you may not have privileges to install pandas into a system folder. A solution is to instead install the module to a user folder. Type:

Now (hopefully), pandas should have installed in a user directory, and will be available for use in your Python/arcpy scripts. To confirm, type the following commands in a new command prompt window:

python import arcpy import pandas 

If arcpy and pandas both import successfully, you’re ready to begin writing scripts that integrate commands from both the arcpy and pandas modules. You also now know how to use pip to easily install any other user-written Python module you might want to use.

About

Tutorial for how to get started scripting with python and arcpy

Источник

Написание скриптов в ArcGIS API for Python

ArcGIS API for Python используется для автоматизации общих задач, таких как создание и управление пользователями и группами, публикация и обновление элементов, мониторинг использования сервера, выполнение сложной визуализации и анализа данных и переход владения элементами. Она также позволяет создавать скрипты для выполнения сложных задач, таких как клонирование ресурсов портала.

В дополнение к скриптам пакетной обработки, API может использоваться в интерактивной среде создания скриптов на основе браузера, называющейся Jupyter Notebook . Среда Notebook предлагает интерфейс для проверки и выполнения кода, визуализации элементов портала, пользователей и групп, а также для интерактивного просмотра веб-слоев, карт и сцен.

Esri предлагает среду Jupyter Notebook , встроенную в ArcGIS Enterprise . Впервые представленная в версии 10.7, ArcGIS Notebooks размещена на ArcGIS Notebook Server , который использует контейнеры для изоляции каждой рабочей области пользователя блокнота. С помощью ArcGIS Notebooks вы можете использовать ArcGIS API for Python и ArcPy для работы с элементами портала, выполнения расширенного пространственного анализа и сложных рабочих процессов изучения данных.

API построен в виде модулей, что облегчает его изучение и использование. Модуль gis является стартовой точкой и предлагает информационную модель для доступа к порталу и для его программирования. Модуль gis содержит многочисленные классы, которые можно использовать для создания пользователей, их групп и элементов, а также для управления ими. Модули features и raster позволяют работать с векторными и растровыми слоями, а также выполнять анализ таких слоев. Модуль geoanalytics позволяет запускать инструменты GeoAnalytics Tools . Дополнительные сведения об остальных модулях и архитектуре API см. в разделе Обзор API.

Начало работы

API распространяется в виде пакета Python и может быть установлен с помощью conda, популярного пакета и системы управления средой Python . Инструкции по установке находятся на сайте ArcGIS Developer .

Источник

Оцените статью