2

I import a .py file like so:

import sys
sys.path.append('/foo/bar/boo/far/')
# import foobar.py from target folder
import foobar

This line (simplified for sharing) works when the code is typed directly in the action editor window instead of importing the external script:

ft = lyr.getFeature([% $id %])

But when I use the same line in the external script, a syntax error is being thrown:

 ft = lyr.getFeature([% $id %])
 ^
SyntaxError: invalid syntax

I continued with direct coding inside the action editor, which is possible of course, but working with an external script would significantly save time!

Any thoughts?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Apr 19, 2023 at 19:57

1 Answer 1

7

[% $id %] is special QGIS syntax for "before sending this text as code to the Python interpreter, insert the value of the QGIS expression $id" here.

A Python interpreter does not know about QGIS' special [%%] syntax and thus will stumble.

You will need to provide the ID value in a normal Python way there.

winnewoerp
1,74912 silver badges24 bronze badges
answered Apr 19, 2023 at 20:58
3
  • Thank you! That definitely helps for finding a solution. I'm still (almost) a PyQGIS newbie. Is iface the way to go here, using iface.activeLayer() to access the action's layer? And is there an iface way to access the clicked feature? I tried to find "a normal Python way" but did not find it so far. Commented Apr 20, 2023 at 4:51
  • 2
    Please create new questions (one question per question) for your other enquiries, as they have no relation to your original post here. It helps to keep Questions and Answers concise and to the point, otherwise things will become jumbled. Commented Apr 20, 2023 at 7:53
  • Thanks, Matt. That's what I did now: https://gis.stackexchange.com/questions/458133/identify-clicked-feature-in-external-python-script-for-qgis-layer-action Commented Apr 20, 2023 at 23:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.