Stdout of modules (e.g. mapproject) using pygmt.clib.Session.call_module

Using gmt 6 (in bash), normally if I want to know the height of my current map I can get it from the stdout of mapproject, i.e.,

map_height=$(gmt mapproject -Wh)

I’m not sure how to access this in PyGMT. I tried

with pygmt.clib.Session() as session:
    map_height = session.call_module('mapproject', '-Wh')

but that gave me a value of “None”.

Is there a way to access the stdout when calling a module with session.call_module? Sorry if I’m being dense about this, I don’t really understand how it works!

Hi @tmerry,

So with pygmt.clib.Session().call_module, you’ll need to redirect the stdout into a temporary file first using ->somefile.txt. Something like so:

import pygmt

fig = pygmt.Figure()
fig.basemap(region=[0, 3, 6, 9], frame=True)
with pygmt.clib.Session() as session:
    with pygmt.helpers.GMTTempFile() as tmpfile:
        session.call_module("mapproject", f"-Wh ->{tmpfile.name}")
        map_height = tmpfile.read().strip()
print(map_height)  # 15

Hopefully that helps! This is based off of similar code in the PyGMT source (e.g. for pygmt.which).

2 Likes