2

I need to count how many times I executed a Pyhthon script in QGIS and I would like to do so by using a project variable as counter. However, I can only create them as string, thus I can't perform mathematical operations with them (count = count + 1).

Is it possible to change their type to integer or to create a counter using pygqis?

2 Answers 2

2
prj = QgsProject.instance()
QgsExpressionContextUtils.setProjectVariable(prj,'counter',"0")
counter=int(QgsExpressionContextUtils.projectScope(prj).variable('counter'))
QgsExpressionContextUtils.setProjectVariable(prj,'counter',counter+1)

The first line finds the current project (needed for QGIS >= 3). The next line initializes to zero, the last 2 lines read and set the counter incremented by one.

3
  • Written at same time as @Spacedman 's answer - he's focusing on the str/int conversion, the above adds the PyQGIS variable part.
    – Houska
    Jun 24, 2019 at 16:05
  • It worked! Thank you. Jun 24, 2019 at 16:07
  • I'd assumed the poster knew how to create string project variables, and I used an explicit str conversion instead of what I suspect is a coercion somewhere to string in your last line. But yay it works!
    – Spacedman
    Jun 24, 2019 at 17:37
2

Convert between strings and integers with str and int:

>>> x = "1"
>>> str(int(x) + 1)
'2'
>>> 

So you'll be storing the string representation of your count as a string. Convert back to int when you retrieve it, and convert back to string when you store it.

Beware of errors if converting non-valid strings to ints:

>>> int("s")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 's'
1
  • Actually I faced the error you mentioned, but @Houska answer helped me. Thank you for your time. Jun 24, 2019 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.