9.1. Занятие: Установка и управление плагинами
TДля того, чтобы начать использовать плагины, вам нужно знать, как их загрузить, устанавливать и активировать. Вы научитесь использовать Plugin Installer и Plugin Manager .
Цель этого урока: Понять и использовать систему плагинов QGIS.
9.1.1. Идем дальше: Управление плагинами

- Для того, чтобы открыть Plugin Manager надо кликнуть на пункту меню Plugins ► Manage and Install Plugins .
- В открывшемся диалоговом окне вам надо найти плагин Processing plugin:
- Кликните на ячейку рядом с этим плагином и снимите флажок, чтобы деактивировать его.
- Кликните на кнопку Close .
- Посмотрите на меню, вы заметите, что меню Processing исчезло. Это означает, что многие из функций обработки, которыми вы пользовались ранее, исчезли! Например, посмотрите на меню Vector ► и Raster ► . Это из-за того, что они являются частью плагина Processing , который необходимо активировать, чтобы использовать их.
- Откройте снова Plugin Manager и активируйте плагин Processing , отметив галочку в ячейке рядом с ним.
- Close диалоговое окно. Меню Processing функции снова должны стать доступными.
9.1.2.
Идем дальше: Установка новых плагинов
Список плагинов, которые вы можете активировать и деактивировать, получен из плагинов, которые вы в настоящее время установили. Для того, чтобы установить новые плагины вам надо:
- Выберите опцию Not Installed в диалоговом окне Plugin Manager . Плагины, доступные для установки, будут показаны в списке. Этот список будет отличаться в зависимости от вашей существующей настройки системы.

- Найдите сведения о плагине, выбрав его в списке.

- Установите те плагины, которые вас интересуют, нажав на кнопку Install Plugin под панелью сведений о плагине.
Если в плагине есть ошибка, он будет в списке закладки Invalid . Вы сможете связаться с владельцем плагина, чтобы решить проблему.
9.1.3.
Идем дальше: Настройка дополнительных репозиториев плагинов
Набор плагинов, доступных для вас, зависит от того, на какие репозитории плагинов настроена ваша система.
Плагины QGIS хранятся в онлайн репозиториях. По умолчанию только ` официальный репозиторий ` _ является активным и это означает, что вы можете получить доступ только к тем плагинам, которые там опубликованы. С учетом разнообразия доступных инструментов, этот репозиторий должен удовлетворить большинство ваших потребностей.
Тем не менее, вы сможете попробовать больше плагинов, чем те, которые доступны по умолчанию. Во-первых, вам надо настроить дополнительные репозитории. Для того чтобы сделать это, необходимо:
- Открыть вкладку Settings в диалоговом окне Plugin Manager .

- Надо кликнуть на Add чтобы найти и добавить новый репозиторий.
- Укажите название или адрес сайта нового репозитория, который вы хотите настроить, и убедитесь, что отмечена галочка в ячейке Enabled .

- Вы теперь увидите репозиторий нового плагина в списке настроенных репозиториев плагинов.

- Вы также можете выбрать опцию отображения Экспериментальных плагинов, выбрав флажок Show also experimental plugins .
- Если вы теперь вернетесь обратно на вкладку Not Installed , то вы увидите, что появились дополнительные плагины для установки.
- Для того, чтобы установить плагин, кликните на него в списке, а затем на кнопку Install plugin .
9.1.4. В заключении
Установка плагинов в QGIS должна быть легкой и эффективной!
9.1.5. Что дальше?
Далее мы расскажем вам о некоторых полезных плагинах в качестве примеров.
Первые шаги в программировании на Python¶
QGIS имеет мощный интерфейс программирования, который позволяет расширить базовую функциональность программного обеспечения, а также писать скрипты для автоматизации заданий. QGIS поддерживает популярный язык сценариев Python. Даже если вы новичок, ознакомление с Python и программным интерфейсом QGIS позволит вам быть гораздо более продуктивным в работе. Этот урок не требует никаких предварительных знаний программирования и предназначен для того, чтобы дать введение в написание сценариев Python в QGIS (PyQGIS).
Обзор задачи¶
Мы загрузим точечный векторный слой, представляющий все крупные аэропорты и используем сценарий Python для создания текстового файла с названием, кодом, широтой и долготой для каждого аэропорта в слое.
Получение данных¶
Методика¶
- В QGIS, перейдите в меню Layers ‣ Add Vector Layer . Перейдите к загруженному файлу ne_10m_airports.zip и нажмите Open . Выберите слой ne_10m_airports.shp и нажмите OK .

- Вы увидите слой ne_10m_airports , загруженный в QGIS.

- Выберите инструмент Identify и нажмите на любую из точек, чтобы изучить доступные атрибуты. Вы увидите, что имя аэропорта и его 3-значный код содержатся в атрибутах name и data_code соответственно.

- QGIS предоставляет встроенную консоль, где вы можете ввести команды Python и получить результат. Эта консоль является отличным способом научиться писать сценарии, а также производить быструю обработку данных. Откройте Python Console , перейдя к меню Plugins ‣ Python Console .

- Вы увидите, что в нижней части окна QGIS открылась новая панель. Вы увидите символы >>> внизу, после которых вы можете вводить команды. Для взаимодействия со средой QGIS мы должны использовать переменную iface . Чтобы получить доступ к текущему активному слою в QGIS, вы можете ввести следующую команду и нажать Enter . Эта команда получает ссылку на текущий загруженный слой и сохраняет её в переменной layer .
layer = iface.activeLayer()

- There is a handy function called dir() in python that shows you all available methods for any object. This is useful when you are not sure what functions are available for the object. Run the following command to see what operations we can do on the layer variable.
dir(layer)

- You will see a long list of available functions. For now, we will use a function called getFeatures() which will gets you the reference to all features of a layer. In our case, each feature will be a point representing an airport. You can type the following command to iterate through each of the features in the current layer. Make sure to add 2 spaces before typing the second line.
for f in layer.getFeatures(): print f

- As you will see in the output, each line contains a reference to a feature within the layer. The reference to the feature is stored in the f variable. We can use the f variable to access the attributes of each feature. Type the following to print the name and iata_code for each airport feature.
for f in layer.getFeatures(): print f['name'], f['iata_code']

- So now you know how to programatically access the attribute of each feature in a layer. Now, let’s see how we can access the coordinates of the feature. The coordinates of a vector feature can be accessed by calling the geometry() function. This function returns a geometry object that we can store in the variable geom . You can run asPoint() function on the geometry object to get the x and y coordinates of the point. If your feature is a line or a polygon, you can use asPolyline() or asPolygon() functions. Type the following code at the prompt and press Enter to see the x and y coordinates of each feature.
for f in layer.getFeatures(): geom = f.geometry() print geom.asPoint()

- What if we wanted to get only the x cordinate of the feature? You can call the x() function on the point object and get its x coordinate.
for f in layer.getFeatures(): geom = f.geometry() print geom.asPoint().x()

- Now we have all the pieces that we can stitch together to generate our desired output. Type the following code to print the name, iata_code, latitude and longitude of each of the airport features. The %s and %f notations are ways to format a string and number variables.
for f in layer.getFeatures(): geom = f.geometry() print '%s, %s, %f, %f' % (f['name'], f['iata_code'], geom.asPoint().y(), geom.asPoint().x())

- You can see the output printed on the console. A more useful way to store the output would be in a file. You can type the following code to create a file and write the output there. Replace the file path with a path on your own system. Note that we add \n at the end of our line formatting. This is to add a newline after we add the data for each feature. You should also note the unicode_line = line.encode(‘utf-8’) line. Since our layer contains some features with unicode characters, we can’t simply write it to a text file. We encode the text using the UTF-8 encoding and then write to the text file.
output_file = open('c:/Users/Ujaval/Desktop/airports.txt', 'w') for f in layer.getFeatures(): geom = f.geometry() line = '%s, %s, %f, %f\n' % (f['name'], f['iata_code'], geom.asPoint().y(), geom.asPoint().x()) unicode_line = line.encode('utf-8') output_file.write(unicode_line) output_file.close()

- You can go to the output file location you specified and open the text file. You will see the data from the airports shapefile that we extracted using python scripting.

© Copyright 2021, Ujaval Gandhi.
Обновлено: нояб. 08, 2023.
Created using Sphinx 7.0.1.
Как включить python в qgis



Скачай курс
в приложении
Перейти в приложение
Открыть мобильную версию сайта
© 2013 — 2023. Stepik
Наши условия использования и конфиденциальности

Public user contributions licensed under cc-wiki license with attribution required
GIS & Geospatial Data Services
Getting started with using Python to automate QGIS workflows can be a bit of a challenge at first, but fortunately the resources below can help accelerate the learning process and are really helpful to refer to even if you are an expert Python user. The PyQGIS cookbook is the best place to start for learning how to utilize the QGIS Python libraries in your scripts while the PyQGIS API documentation is an extremely useful comprehensive guide that describes every class and method that the API provides access to.
If you are looking for general Python documentation and tutorials to help build up your Python skills in preparation for GIS related scripting you may want to visit the following websites which offer useful resources to Python learners.
Configuring QGIS and Python on a Windows Computer
Please note that portions of the text that are colored red in the instructions below should be modified after copying and pasting to reflect the correct version of QGIS that you have installed on your computer.
- Install the standalone QGIS application (not the OS Geo bundle with QGIS) from https://qgis.org/en/site/forusers/download.html if you have not done so already
- Identify the path to the Python executable that was installed with QGIS (it should be at C:\Program Files\ QGIS 3.14 \apps\Python37). Navigate to this location in your file system and make a duplicate copy of the python.exe file. Name this duplicate copy of the Python executable python3qgis to distinguish it from other installations of Python that might already exist on your computer.
- In the search bar located in the left portion of the task bar at the bottom of your screen, search for «advanced system settings» and then click the «View Advanced System Settings» button that shows up in your results. In the window that appears, click on «Environmental Variables. «. **Please note that you will need administrative privileges on the computer you are working on in order to complete this step.
- In the Environmental Variables window, click on the row for the Path variable under User Settings to highlight it in blue. Add the path to the QGIS Python executable (which you copied in step 2 above) to your path, by clicking the Edit button, than the New button, and pasting in the QGIS Python executable path in the blank row that your cursor has been moved to. Once you have done this click OK to return to the Environmental Variables window
- Now click the New button under User Variables. In the new window that appears, type PYTHONPATH for the Variable Name and paste C:\Program Files\ QGIS 3.14 \apps\qgis\python;C:\Program Files\ QGIS 3.14 \apps\qgis\python\plugins;C:\Program Files\ QGIS 3.14 \apps\Qt5\plugins;C:\Program Files\ QGIS 3.14 \share\gdal; in the Variable Value field, then click OK.
- Now click OK in the Environmental Variables window and in the System Settings window to save the changes that you’ve made.
- To verify your QGIS Python instance can now be run outside of the QGIS environment and used to develop external scripts, open a new Command Prompt window. In this new window type python3qgis. This will start Python in the Command Prompt environment. Now type from qgis.core import * and press Enter on your keyboard. If you see your Command Prompt jump down to a new line after a few seconds without generating an error than you have verified that you are able to QGIS Python libraries in your script.
- You should now be able to use any integrated development environment (IDE) software to write a Python script that utilizes QGIS Python libraries. To make sure that your IDE calls the correct Python executable for any scripts that you write, make sure the path to its default Python installation is the path python3qgis Python executable that was created in step 2 above. Before starting a new script make sure that you refer to https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html#using-pyqgis-in-standalone-scripts as this contains essential information about structuring your script to ensure that the QGIS Python libraries can be used successfully. If you do not already have an IDE application installed that can be used for Python development you can continue with the steps below which describe how to install and use Atom to create and run Python scripts that reference QGIS Python libraries.
- Visit https://atom.io/ and click the Download button to download the Atom installation files on your computer. Double click on the installion file to install Atom.
- After Atom has finished installing, open the application. Click on File > Settings to open the application settings window. In the Settings window, click the Install button and then in the search bar that appears on the Install page type atom python run. The atom-python-run package should be the first one that appears in a list of search results. Click the Install button for the atom-python-run package. Once it is installed, click the Settings button for this package. On the package settings page find the text field under the F5 Comman heading, and paste in the following text: python3qgis . This configuration will allow you to easily run a script that you are working on in Atom using the python3qgis Python executable on your computer by hitting the F5 button on you keyboard.
- Now that the atom-python-run package has been configured, click File > New File to create a new blank Python script file for you to work in. This file will open in a new tab within Atom. As soon as it opens click FIle > Save to open the file save window. In this window selection the location on your file system where you want the script to be stored and select a name for you script. Please note that the file name must end in .py in order for it to be correctly treated as a Python file.
- Once your script has been successfully saved, you can now start to write your Python code in the file. If you want to verify that everything is working correctly type the following for your first line of code: from qgis.core import *. Next, hit the F5 button on your keyboard to automatically save and run the script (please note you may need to make sure that the Fn button on your keyboard is on for the F5 key to call the function correctly). If everything is working properly you should see a Python shell appear. After a few seconds the text Process returned 0 (0x0) execution time : 0.123 s should appear in the shell if the code was executed successfully and the QGIS core library was imported without any issues. If instead of this message you notice an error or the Python does not appear at all when you hit F5, please review the instructions above to look for any place where a step might have been missed. If everything is working correctly you can now proceed with writing your script
Configuring QGIS and Python on a Mac
Please note that portions of the text that are colored red in the instructions below should be modified after copying and pasting to reflect the correct version of QGIS that you have installed on your computer.
- Install the latest version of the standalone QGIS application from https://qgis.org/en/site/forusers/download.html if you do not already have it on your system. Please not that these instructions may not work for older version of QGIS installed on a Mac.
- Go to your applications folder, right click on QGIS, click «Show Contents», and navigate to /Applications/QGIS.app/Contents/MacOS/bin/ to make sure that this path exists
- Open terminal and paste in:
/Applications/QGIS.app/Contents/MacOS/bin/python3.8
then hit Enter on your keyboard. This should open the Python interpreter that was installed with QGIS in your terminal. Now that you have activated the Python interpreter in the Terminal, type the following:
from qgis.core import *
then hit Enter on your keyboard. If you don’t receive an error after running this line of code, that is an indication that the path to your QGIS Python interpreter is correct and your Python environment is successfully configured. - Visit https://atom.io/ and click the Download button to download the Atom installation files on your computer. Double click on the installion file to install Atom.
- After Atom has finished installing, open the application. Click on File > Settings to open the application settings window. In the Settings window, click the Install button and then in the search bar that appears on the Install page type atom python run. The atom-python-run package should be the first one that appears in a list of search results. Click the Install button for the atom-python-run package. Once it is installed, click the Settings button for this package. On the package settings page find the text field under the F5 Command heading, and paste in the following text: /Applications/QGIS.app/Contents/MacOS/bin/python3.8 . This configuration will allow you to easily run a script that you are working on in Atom using the QGIS Python installation on your computer by hitting the F5 button on you keyboard.
- Now that the atom-python-run package has been configured, click File > New File to create a new blank Python script file for you to work in. This file will open in a new tab within Atom. As soon as it opens click FIle > Save to open the file save window. In this window selection the location on your file system where you want the script to be stored and select a name for you script. Please note that the file name must end in .py in order for it to be correctly treated as a Python file.
- Once your script has been successfully saved, you can now start to write your Python code in the file. If you want to verify that everything is working correctly type the following for your first line of code: from qgis.core import *. Next, hit the F5 button on your keyboard to automatically save and run the script (please note you may need to make sure that the Fn button on your keyboard is on for the F5 key to call the function correctly). If everything is working properly you should see a Python shell appear. After a few seconds the text Process returned 0 (0x0) execution time : 0.123 s should appear in the shell if the code was executed successfully and the QGIS core library was imported without any issues. If instead of this message you notice an error or the Python does not appear at all when you hit F5, please review the instructions above to look for any place where a step might have been missed. If everything is working correctly you can now proceed with writing your script edit the settings for atom python run and for the F5 key set the configuration to
