[GRASS-dev] Python scripts in GRASS GIS: conditional loading of external libraries?

Nikos Alexandris nik at nikosalexandris.net
Fri Oct 19 09:24:38 PDT 2018


* Markus Neteler <neteler at osgeo.org> [2018-10-19 16:45:29 +0200]:

>Hi,
>
>we are currently writing a Python script which needs to import some
>heavy external libraries.
>AFAIK the script is read twice, once by the Python interpreter, then
>when having reached the grass.parser() line again in order to re-read
>properly the
>#% options ...
>etc. statements.
>
>Now: could the import of the external library (it takes in the range
>of > 2min) be conditionalized to only be read at the second "run"?
>
>I was searching in the g.parser code but didn't really find anything useful.
>An example would also be fine (addon?).
>
>Or am I on the wrong track?

An idea is to try make use of `importlib.import_module()` along with
`sys`, like:

```
import sys
import importlib
if 'xyz' not in sys.modules:
    importlib.import_module('xyz')
```
or better (?):

```
if 'xyz' not in sys.modules and 'xyz' not in dir():
    importlib.import_module('xyz')
```

Although this is a valid test, according to some answers over at
StackExchange, I still miss something to make it work.

In ipython, the import works, but I am not able to access interactively
'xyz.' methods though.

Note to self: understand why.

Nikos
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 228 bytes
Desc: not available
URL: <http://lists.osgeo.org/pipermail/grass-dev/attachments/20181019/3c18230b/attachment.sig>


More information about the grass-dev mailing list