Skip to content

Commit 9ccb076

Browse files
committed
new robust getcwd
1 parent f3b0912 commit 9ccb076

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

nipype/utils/misc.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77
absolute_import)
88
from builtins import next, str
99

10+
import os
1011
import sys
1112
import re
1213
from collections import Iterator
14+
from warnings import warn
1315

1416
from distutils.version import LooseVersion
1517

@@ -301,3 +303,25 @@ def dict_diff(dold, dnew, indent=0):
301303
diff.insert(diffkeys, "Some dictionary entries had differing values:")
302304

303305
return textwrap_indent('\n'.join(diff), ' ' * indent)
306+
307+
308+
def rgetcwd(error=True):
309+
"""
310+
Robust replacement for getcwd when folders get removed
311+
If error==True, this is just an alias for os.getcwd()
312+
"""
313+
if error:
314+
return os.getcwd()
315+
316+
try:
317+
cwd = os.getcwd()
318+
except OSError as exc:
319+
# Changing back to cwd is probably not necessary
320+
# but this makes sure there's somewhere to change to.
321+
cwd = os.getenv('PWD')
322+
if cwd is None:
323+
raise OSError((
324+
exc.errno, 'Current directory does not exist anymore, '
325+
'and nipype was not able to guess it from the environment'))
326+
warn('Current folder does not exist, replacing with "%s" instead.' % cwd)
327+
return cwd

nipype/utils/tests/test_misc.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
from future import standard_library
55
standard_library.install_aliases()
66

7+
import os
8+
from shutil import rmtree
79
from builtins import next
810

911
import pytest
@@ -60,3 +62,30 @@ def test_flatten():
6062

6163
back = unflatten([], [])
6264
assert back == []
65+
66+
67+
def test_rgetcwd(monkeypatch, tmpdir):
68+
from ..misc import rgetcwd
69+
oldpath = tmpdir.strpath
70+
tmpdir.mkdir("sub").chdir()
71+
newpath = os.getcwd()
72+
73+
# Path still there
74+
assert rgetcwd() == newpath
75+
76+
# Remove path
77+
rmtree(newpath, ignore_errors=True)
78+
with pytest.raises(OSError):
79+
os.getcwd()
80+
81+
monkeypatch.setenv('PWD', oldpath)
82+
assert rgetcwd(error=False) == oldpath
83+
84+
# Test when error should be raised
85+
with pytest.raises(OSError):
86+
rgetcwd()
87+
88+
# Deleted env variable
89+
monkeypatch.delenv('PWD')
90+
with pytest.raises(OSError):
91+
rgetcwd(error=False)

0 commit comments

Comments
 (0)