Python Forum

Full Version: NameError: name 'processing' is not defined
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello python experts
I use to run this piece of code in QGIS, but it has been awhile (6 months)
It has been working perfect before but now I get this error that I can not solve.

"processing" is not defined, is the error message

Is this related to this code or I have to look into QGIS groups for an answer?

Thank you
Regards

from datetime import datetime

trolls = '/Users/username/Desktop/test.gpkg|layername=test'

rules_per_code = {
    'FA_058': [("Ordertype = 2 AND PLD_1 = 1", 53),
               ("Ordertype = 5 AND PLD_1 = 2", 78)],
    'FA_030': [("Ordertype = 2 AND PLD_1 = 1", 32),
               ("Ordertype = 5 AND PLD_1 = 2", 54)]
    }

results = {}
my_timestamp = datetime.strftime(datetime.now(),'%Y%m%d_%H%M%S')

for code, rules in rules_per_code.items():
    print('Processing {} ...'.format(code))
    results[code] = []
    for rule in rules:
        expression = rule[0]
        percentage = rule[1]
        extracted = processing.run("native:extractbyexpression",
            {'INPUT':trolls,'EXPRESSION':expression,'OUTPUT':'memory:'}
            )['OUTPUT']
        random_sample = processing.run("qgis:randomextract",
            {'INPUT':extracted,'METHOD':1,'NUMBER':percentage,'OUTPUT':'memory:'}
            )['OUTPUT']
        results[code].append(random_sample)

for code, results in results.items():
    merged = processing.run("native:mergevectorlayers", 
        {'LAYERS':results,'CRS':None,
        'OUTPUT':'/Users/username/Desktop/{}_{}.gpkg'.format(code,my_timestamp)}
        )['OUTPUT']
    iface.addVectorLayer(merged, '', 'ogr')  
Indeed, on line 21, processing is referred to, but not defined anywhere prior to that. Where should it come from? It it a module that you import, or should it be a variable you create? I can't say I know anything about GIS, so can't help you there.

You should get into the habit of keeping track of changes to your source code by using some kind of version control system (e.g. Git). That way, you'd at least have a log of what you changed, when and why and could go back to an earlier version if needed. It's also useful if you want to work with others on the same codebase.
OK thanks,
Python is part of QGIS and it calls process-modules like "native:extractbyexpression".
I have not build this myself, something must have been changed in later versions...

Might see if I can go back to an earlier version and see if that helps or see if someone in QGIS groups can give me a hint.

Regards