Skip to content

Commit a16b7eb

Browse files
committed
add from builtins import open where needed, fixed some open and never closed files
1 parent ce2274e commit a16b7eb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+137
-108
lines changed

Diff for: circle.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ dependencies:
2626

2727
test:
2828
override:
29+
- docker run -v /etc/localtime:/etc/localtime:ro -v ~/scratch:/scratch -w /root/src/nipype/doc nipype/nipype_test:py35 /usr/bin/run_builddocs.sh
2930
- docker run -v /etc/localtime:/etc/localtime:ro -e FSL_COURSE_DATA="/root/examples/nipype-fsl_course_data" -v ~/examples:/root/examples:ro -v ~/scratch:/scratch -w /root/src/nipype nipype/nipype_test:py35 /usr/bin/run_nosetests.sh :
3031
timeout: 2600
31-
- docker run -v /etc/localtime:/etc/localtime:ro -v ~/scratch:/scratch -w /root/src/nipype/doc nipype/nipype_test:py35 /usr/bin/run_builddocs.sh
3232
- docker run -v /etc/localtime:/etc/localtime:ro -v ~/examples:/root/examples:ro -v ~/scratch:/scratch -w /scratch nipype/nipype_test:py35 /usr/bin/run_examples.sh test_spm Linear /root/examples/ workflow3d :
3333
timeout: 1600
3434
- docker run -v /etc/localtime:/etc/localtime:ro -v ~/examples:/root/examples:ro -v ~/scratch:/scratch -w /scratch nipype/nipype_test:py35 /usr/bin/run_examples.sh test_spm Linear /root/examples/ workflow4d :

Diff for: doc/sphinxext/autosummary_generate.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
./ext/autosummary_generate.py -o source/generated source/*.rst
1717
1818
"""
19+
from __future__ import print_function, unicode_literals
20+
from builtins import open
1921

20-
from __future__ import print_function
21-
import glob
2222
import re
2323
import inspect
2424
import os

Diff for: examples/fmri_ants_openfmri.py

+9-15
Original file line numberDiff line numberDiff line change
@@ -12,35 +12,30 @@
1212
python fmri_ants_openfmri.py --datasetdir ds107
1313
"""
1414
from __future__ import division, unicode_literals
15-
from builtins import range, str, bytes
16-
17-
from nipype import config
18-
config.enable_provenance()
19-
15+
from builtins import open, range, str, bytes
2016

2117
from glob import glob
2218
import os
2319

20+
from nipype import config
21+
from nipype import LooseVersion
22+
from nipype import Workflow, Node, MapNode
23+
from nipype.utils.filemanip import filename_to_list
2424
import nipype.pipeline.engine as pe
2525
import nipype.algorithms.modelgen as model
2626
import nipype.algorithms.rapidart as ra
2727
from nipype.algorithms.misc import TSNR
2828
from nipype.interfaces.c3 import C3dAffineTool
29+
from nipype.interfaces import fsl, Function, ants, freesurfer as fs
2930
import nipype.interfaces.io as nio
31+
from nipype.interfaces.io import FreeSurferSource
3032
import nipype.interfaces.utility as niu
33+
from nipype.interfaces.utility import Merge, IdentityInterface
3134
from nipype.workflows.fmri.fsl import (create_featreg_preproc,
3235
create_modelfit_workflow,
3336
create_fixed_effects_flow)
3437

35-
from nipype import LooseVersion
36-
from nipype import Workflow, Node, MapNode
37-
from nipype.interfaces import (fsl, Function, ants, freesurfer)
38-
39-
from nipype.interfaces.utility import Merge, IdentityInterface
40-
from nipype.utils.filemanip import filename_to_list
41-
from nipype.interfaces.io import FreeSurferSource
42-
import nipype.interfaces.freesurfer as fs
43-
38+
config.enable_provenance()
4439
version = 0
4540
if fsl.Info.version() and \
4641
LooseVersion(fsl.Info.version()) > LooseVersion('5.0.6'):
@@ -56,7 +51,6 @@
5651
'from scipy.special import legendre'
5752
]
5853

59-
6054
def median(in_files):
6155
"""Computes an average of the median of each realigned timeseries
6256

Diff for: examples/rsfmri_vol_surface_preprocessing.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@
4343
- `MNI template <http://mindboggle.info/data/templates/ants/OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz>`_
4444
"""
4545

46-
from __future__ import division
47-
from __future__ import unicode_literals
46+
from __future__ import division, unicode_literals
4847
from builtins import open, range
4948

5049
import os

Diff for: examples/rsfmri_vol_surface_preprocessing_nipy.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@
4444
4545
"""
4646

47-
from __future__ import division
48-
from __future__ import unicode_literals
47+
from __future__ import division, unicode_literals
4948
from builtins import open, range
5049

5150
import os

Diff for: examples/smri_ants_build_template.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
1. Tell python where to find the appropriate functions.
1313
"""
1414

15-
from __future__ import print_function
15+
from __future__ import print_function, unicode_literals
16+
from builtins import open
1617
from future import standard_library
1718
standard_library.install_aliases()
1819

Diff for: examples/smri_ants_registration.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@
1111
1212
1. Tell python where to find the appropriate functions.
1313
"""
14+
from __future__ import print_function, unicode_literals
15+
from builtins import open
1416

15-
from __future__ import print_function
1617
from future import standard_library
1718
standard_library.install_aliases()
1819

Diff for: nipype/algorithms/misc.py

+19-15
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
1313
'''
1414
from __future__ import print_function, division, unicode_literals, absolute_import
15-
from builtins import str, zip, range
15+
from builtins import str, zip, range, open
1616
from future.utils import raise_from
1717

1818
import os
@@ -236,15 +236,17 @@ def _gen_output_file_name(self):
236236
return os.path.abspath(base + ".nii")
237237

238238
def _run_interface(self, runtime):
239-
hdr = nb.AnalyzeHeader.from_fileobj(
240-
open(self.inputs.header_file, 'rb'))
239+
with open(self.inputs.header_file, 'rb') as hdr_file:
240+
hdr = nb.AnalyzeHeader.from_fileobj(hdr_file)
241241

242242
if isdefined(self.inputs.affine):
243243
affine = self.inputs.affine
244244
else:
245245
affine = None
246246

247-
data = hdr.data_from_fileobj(open(self.inputs.data_file, 'rb'))
247+
with open(self.inputs.header_file, 'rb') as data_file:
248+
data = hdr.data_from_fileobj(data_file)
249+
248250
img = nb.Nifti1Image(data, affine, hdr)
249251
nb.save(img, self._gen_output_file_name())
250252

@@ -364,11 +366,9 @@ def _gen_output_file_name(self):
364366

365367
def _run_interface(self, runtime):
366368
import gzip
367-
in_file = gzip.open(self.inputs.in_file, 'rb')
368-
out_file = open(self._gen_output_file_name(), 'wb')
369-
out_file.write(in_file.read())
370-
out_file.close()
371-
in_file.close()
369+
with gzip.open(self.inputs.in_file, 'rb') as in_file:
370+
with open(self._gen_output_file_name(), 'wb') as out_file:
371+
out_file.write(in_file.read())
372372
return runtime
373373

374374
def _list_outputs(self):
@@ -501,8 +501,9 @@ def merge_csvs(in_list):
501501
try:
502502
in_array = np.loadtxt(in_file, delimiter=',', skiprows=1)
503503
except ValueError as ex:
504-
first = open(in_file, 'r')
505-
header_line = first.readline()
504+
with open(in_file, 'r') as first:
505+
header_line = first.readline()
506+
506507
header_list = header_line.split(',')
507508
n_cols = len(header_list)
508509
try:
@@ -681,8 +682,8 @@ def _run_interface(self, runtime):
681682
ext = '.csv'
682683

683684
out_file = op.abspath(name + ext)
684-
file_handle = open(out_file, 'w')
685-
file_handle.write(csv_headings)
685+
with open(out_file, 'w') as file_handle:
686+
file_handle.write(csv_headings)
686687

687688
shape = np.shape(output_array)
688689
typelist = maketypelist(
@@ -711,8 +712,9 @@ def _run_interface(self, runtime):
711712
output[extraheading] = extrafieldlist
712713
iflogger.info(output)
713714
iflogger.info(fmt)
714-
np.savetxt(file_handle, output, fmt, delimiter=',')
715-
file_handle.close()
715+
with open(out_file, 'a') as file_handle:
716+
np.savetxt(file_handle, output, fmt, delimiter=',')
717+
716718
return runtime
717719

718720
def _list_outputs(self):
@@ -774,6 +776,8 @@ def _run_interface(self, runtime):
774776
new_line = line.replace('\n', '')
775777
new_line = new_line + ',' + self.inputs.extra_field + '\n'
776778
out_file.write(new_line)
779+
in_file.close()
780+
out_file.close()
777781
return runtime
778782

779783
def _list_outputs(self):

Diff for: nipype/caching/memory.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
>>> os.chdir(datadir)
1111
"""
1212
from __future__ import print_function, division, unicode_literals, absolute_import
13-
from builtins import object
13+
from builtins import object, open
1414

1515
import os
1616
import hashlib
@@ -106,11 +106,13 @@ def __repr__(self):
106106
def read_log(filename, run_dict=None):
107107
if run_dict is None:
108108
run_dict = dict()
109-
for line in open(filename, 'r'):
110-
dir_name, job_name = line[:-1].split('/')
111-
jobs = run_dict.get(dir_name, set())
112-
jobs.add(job_name)
113-
run_dict[dir_name] = jobs
109+
110+
with open(filename, 'r') as logfile:
111+
for line in logfile:
112+
dir_name, job_name = line[:-1].split('/')
113+
jobs = run_dict.get(dir_name, set())
114+
jobs.add(job_name)
115+
run_dict[dir_name] = jobs
114116
return run_dict
115117

116118

@@ -226,8 +228,9 @@ def _log_name(self, dir_name, job_name):
226228
# Every counter is a file opened in append mode and closed
227229
# immediately to avoid race conditions in parallel computing:
228230
# file appends are atomic
229-
open(os.path.join(base_dir, 'log.current'),
230-
'a').write('%s/%s\n' % (dir_name, job_name))
231+
with open(os.path.join(base_dir, 'log.current'), 'a') as currentlog:
232+
currentlog.write('%s/%s\n' % (dir_name, job_name))
233+
231234
t = time.localtime()
232235
year_dir = os.path.join(base_dir, 'log.%i' % t.tm_year)
233236
try:
@@ -239,8 +242,9 @@ def _log_name(self, dir_name, job_name):
239242
os.mkdir(month_dir)
240243
except OSError:
241244
"Dir exists"
242-
open(os.path.join(month_dir, '%02i.log' % t.tm_mday),
243-
'a').write('%s/%s\n' % (dir_name, job_name))
245+
246+
with open(os.path.join(month_dir, '%02i.log' % t.tm_mday), 'a') as rotatefile:
247+
rotatefile.write('%s/%s\n' % (dir_name, job_name))
244248

245249
def clear_previous_runs(self, warn=True):
246250
""" Remove all the cache that where not used in the latest run of

Diff for: nipype/interfaces/cmtk/cmtk.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
1111
"""
1212
from __future__ import print_function, division, unicode_literals, absolute_import
13-
from builtins import range
13+
from builtins import range, open
1414

1515
import pickle
1616
import os.path as op
@@ -711,9 +711,8 @@ def _run_interface(self, runtime):
711711

712712
if write_dict:
713713
iflogger.info('Saving Dictionary File to {path} in Pickle format'.format(path=dict_file))
714-
file = open(dict_file, 'w')
715-
pickle.dump(labelDict, file)
716-
file.close()
714+
with open(dict_file, 'w') as f:
715+
pickle.dump(labelDict, f)
717716
return runtime
718717

719718
def _list_outputs(self):

Diff for: nipype/interfaces/diffusion_toolkit/dti.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
1212
"""
1313
from __future__ import print_function, division, unicode_literals, absolute_import
14-
from builtins import range
14+
from builtins import range, open
1515

1616
import os
1717
import re
@@ -71,16 +71,16 @@ class DTIRecon(CommandLine):
7171

7272
def _create_gradient_matrix(self, bvecs_file, bvals_file):
7373
_gradient_matrix_file = 'gradient_matrix.txt'
74-
bvals = [val for val in re.split('\s+', open(bvals_file).readline().strip())]
75-
bvecs_f = open(bvecs_file)
76-
bvecs_x = [val for val in re.split('\s+', bvecs_f.readline().strip())]
77-
bvecs_y = [val for val in re.split('\s+', bvecs_f.readline().strip())]
78-
bvecs_z = [val for val in re.split('\s+', bvecs_f.readline().strip())]
79-
bvecs_f.close()
80-
gradient_matrix_f = open(_gradient_matrix_file, 'w')
81-
for i in range(len(bvals)):
82-
gradient_matrix_f.write("%s, %s, %s, %s\n" % (bvecs_x[i], bvecs_y[i], bvecs_z[i], bvals[i]))
83-
gradient_matrix_f.close()
74+
with open(bvals_file) as fbvals:
75+
bvals = [val for val in re.split('\s+', fbvals.readline().strip())]
76+
with open(bvecs_file) as fbvecs:
77+
bvecs_y = [val for val in re.split('\s+', fbvecs.readline().strip())]
78+
bvecs_z = [val for val in re.split('\s+', fbvecs.readline().strip())]
79+
bvecs_x = [val for val in re.split('\s+', fbvecs.readline().strip())]
80+
81+
with open(_gradient_matrix_file, 'w') as gradient_matrix_f:
82+
for i in range(len(bvals)):
83+
gradient_matrix_f.write("%s, %s, %s, %s\n" % (bvecs_x[i], bvecs_y[i], bvecs_z[i], bvals[i]))
8484
return _gradient_matrix_file
8585

8686
def _format_arg(self, name, spec, value):

Diff for: nipype/interfaces/elastix/utils.py

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
1010
"""
1111
from __future__ import print_function, division, unicode_literals, absolute_import
12+
from builtins import open
1213

1314
import os.path as op
1415

Diff for: nipype/interfaces/freesurfer/tests/test_utils.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# -*- coding: utf-8 -*-
22
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
33
# vi: set ft=python sts=4 ts=4 sw=4 et:
4+
from __future__ import print_function, division, unicode_literals, absolute_import
5+
from builtins import open
46

57
import os
68
from tempfile import mkdtemp

Diff for: nipype/interfaces/fsl/dti.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
1414
"""
1515
from __future__ import print_function, division, unicode_literals, absolute_import
16-
from builtins import range
16+
from builtins import range, open
1717

1818
import os
1919
import warnings

Diff for: nipype/interfaces/fsl/model.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
>>> os.chdir(datadir)
1313
"""
1414
from __future__ import print_function, division, unicode_literals, absolute_import
15-
from builtins import range
15+
from builtins import range, open
1616

1717
import os
1818
from glob import glob

Diff for: nipype/interfaces/fsl/preprocess.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
>>> os.chdir(datadir)
1313
"""
1414
from __future__ import print_function, division, unicode_literals, absolute_import
15-
from builtins import range
15+
from builtins import range, open
1616

1717
import os
1818
import os.path as op

Diff for: nipype/interfaces/minc/minc.py

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
1818
"""
1919
from __future__ import print_function, division, unicode_literals, absolute_import
20+
from builtins import open
2021

2122
import glob
2223
import os

Diff for: nipype/interfaces/mrtrix/convert.py

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
1111
"""
1212
from __future__ import print_function, division, unicode_literals, absolute_import
13+
from builtins import open
1314

1415
import os.path as op
1516
import nibabel as nb

Diff for: nipype/interfaces/nipy/preprocess.py

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
99
"""
1010
from __future__ import print_function, division, unicode_literals, absolute_import
11+
from builtins import open
1112

1213
import os
1314

Diff for: nipype/interfaces/nitime/analysis.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
1212
"""
1313
from __future__ import print_function, division, unicode_literals, absolute_import
14-
15-
from builtins import zip, object
14+
from builtins import zip, object, open
1615

1716
import numpy as np
1817
import tempfile

0 commit comments

Comments
 (0)