Первые шаги в программировании на Python¶
Предупреждение
A new version of this tutorial is available at Getting Started With Python Programming (QGIS3)
QGIS имеет мощный интерфейс программирования, который позволяет расширить базовую функциональность программного обеспечения, а также писать скрипты для автоматизации заданий. QGIS поддерживает популярный язык сценариев Python. Даже если вы новичок, ознакомление с Python и программным интерфейсом QGIS позволит вам быть гораздо более продуктивным в работе. Этот урок не требует никаких предварительных знаний программирования и предназначен для того, чтобы дать введение в написание сценариев Python в QGIS (PyQGIS).
Обзор задачи¶
Мы загрузим точечный векторный слой, представляющий все крупные аэропорты и используем сценарий Python для создания текстового файла с названием, кодом, широтой и долготой для каждого аэропорта в слое.
Получение данных¶
Мы будем использовать набор данных Аэропорты <http://www.naturalearthdata.com/downloads/10m-cultural-vectors/airports/> _ из Natural Earth.
Загрузите shape-файл с аэропортами.
Источник данных: [NATURALEARTH]
Методика¶
В QGIS, перейдите в меню
. Перейдите к загруженному файлуne_10m_airports.zip
и нажмите Open. Выберите слойne_10m_airports.shp
и нажмите OK.

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

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

QGIS предоставляет встроенную консоль, где вы можете ввести команды Python и получить результат. Эта консоль является отличным способом научиться писать сценарии, а также производить быструю обработку данных. Откройте 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 thelayer
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 thef
variable to access the attributes of each feature. Type the following to print thename
andiata_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 variablegeom
. You can runasPoint()
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 useasPolyline()
orasPolygon()
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 thex()
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 theunicode_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.

If you want to report any issues with this tutorial, please comment below. (requires GitHub account)