Skip to content

Commit 88ab1ca

Browse files
authored
Set GMT_SESSION_NAME to a unique name on Windows for partial multiprocessing support (#2938)
1 parent 6028bf4 commit 88ab1ca

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

pygmt/session_management.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
"""
22
Modern mode session management modules.
33
"""
4+
import os
5+
import sys
6+
47
from pygmt.clib import Session
8+
from pygmt.helpers import unique_name
59

610

711
def begin():
@@ -12,6 +16,10 @@ def begin():
1216
1317
Only meant to be used once for creating the global session.
1418
"""
19+
# On Windows, need to set GMT_SESSION_NAME to a unique value
20+
if sys.platform == "win32":
21+
os.environ["GMT_SESSION_NAME"] = unique_name()
22+
1523
prefix = "pygmt-session"
1624
with Session() as lib:
1725
lib.call_module(module="begin", args=prefix)

pygmt/tests/test_session_management.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
"""
22
Test the session management modules.
33
"""
4+
import multiprocessing as mp
45
import os
6+
from importlib import reload
7+
from pathlib import Path
58

69
import pytest
710
from pygmt.clib import Session
@@ -57,3 +60,29 @@ def test_gmt_compat_6_is_applied(capsys):
5760
# Make sure no global "gmt.conf" in the current directory
5861
assert not os.path.exists("gmt.conf")
5962
begin() # Restart the global session
63+
64+
65+
def _gmt_func_wrapper(figname):
66+
"""
67+
A wrapper for running PyGMT scripts with multiprocessing.
68+
69+
Currently, we have to import pygmt and reload it in each process. Workaround from
70+
https://github.com/GenericMappingTools/pygmt/issues/217#issuecomment-754774875.
71+
"""
72+
import pygmt
73+
74+
reload(pygmt)
75+
fig = pygmt.Figure()
76+
fig.basemap(region=[10, 70, -3, 8], projection="X8c/6c", frame="afg")
77+
fig.savefig(figname)
78+
79+
80+
def test_session_multiprocessing():
81+
"""
82+
Make sure that multiprocessing is supported if pygmt is re-imported.
83+
"""
84+
prefix = "test_session_multiprocessing"
85+
with mp.Pool(2) as p:
86+
p.map(_gmt_func_wrapper, [f"{prefix}-1.png", f"{prefix}-2.png"])
87+
Path(f"{prefix}-1.png").unlink()
88+
Path(f"{prefix}-2.png").unlink()

0 commit comments

Comments
 (0)