[GRASS-dev] creating temporary mapsets in a parallelized python script

Pietro peter.zamb at gmail.com
Thu Apr 14 05:39:09 PDT 2016


> The main issue with use_temp_region() is that the clean-up function
> uses the current value of the environment variable to determine which
> region to delete.
>
> This could be fixed by passing a lambda to atexit.register(), e.g.
>
> def use_temp_region():
>     name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
>     run_command("g.region", save=name, overwrite=True)
>     os.environ['WIND_OVERRIDE'] = name
>     atexit.register(lambda: run_command("g.remove", flags='f', quiet=True, type='region', name=name))

Perhaps we could decorate the function with contextmanager:

{{{
from contextlib import contextmanager

@contextmanager
def use_temp_region(**reg):
    name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
    original = region()
    try:
        reg = parse_command("g.region", save=name, overwrite=True, **reg)
        os.environ['WIND_OVERRIDE'] = name
        yield reg
    finally:
        # clean created variable and region
        print('WIND_OVERRIDE' in os.environ)
        os.environ.pop('WIND_OVERRIDE')
        run_command("g.remove", flags='f', quiet=True, type='region', name=name)
        # restore previous region
        for key in 'projection,zone,cells'.split(','):
            original.pop(key)
        run_command("g.region", **original)
}}}

and then use the function with:

{{{
run_command("g.region", flags='p')
print('=' * 30)

with use_temp_region(res=100) as tmp_region:
    run_command("g.region", flags='p')
    print('=' * 30)

run_command("g.region", flags='p')
print('=' * 30)
}}}

All the best

Pietro


More information about the grass-dev mailing list