##// END OF EJS Templates
Fix ResourceWarning: unclosed file...
Mickaël Schoentgen -
Show More
@@ -179,13 +179,14 b' class CrashHandler(object):'
179 print('Could not create crash report on disk.', file=sys.stderr)
179 print('Could not create crash report on disk.', file=sys.stderr)
180 return
180 return
181
181
182 with report:
182 # Inform user on stderr of what happened
183 # Inform user on stderr of what happened
183 print('\n'+'*'*70+'\n', file=sys.stderr)
184 print('\n'+'*'*70+'\n', file=sys.stderr)
184 print(self.message_template.format(**self.info), file=sys.stderr)
185 print(self.message_template.format(**self.info), file=sys.stderr)
185
186
186 # Construct report on disk
187 # Construct report on disk
187 report.write(self.make_report(traceback))
188 report.write(self.make_report(traceback))
188 report.close()
189
189 input("Hit <Enter> to quit (your terminal may close):")
190 input("Hit <Enter> to quit (your terminal may close):")
190
191
191 def make_report(self,traceback):
192 def make_report(self,traceback):
@@ -206,9 +206,8 b' def _file_lines(fname):'
206 except IOError:
206 except IOError:
207 return []
207 return []
208 else:
208 else:
209 out = outfile.readlines()
209 with out:
210 outfile.close()
210 return outfile.readlines()
211 return out
212
211
213
212
214 class Pdb(OldPdb):
213 class Pdb(OldPdb):
@@ -3469,9 +3469,8 b' class InteractiveShell(SingletonConfigurable):'
3469 self.tempfiles.append(filename)
3469 self.tempfiles.append(filename)
3470
3470
3471 if data:
3471 if data:
3472 tmp_file = open(filename,'w')
3472 with open(filename, 'w') as tmp_file:
3473 tmp_file.write(data)
3473 tmp_file.write(data)
3474 tmp_file.close()
3475 return filename
3474 return filename
3476
3475
3477 @undoc
3476 @undoc
@@ -722,7 +722,8 b' class CodeMagics(Magics):'
722
722
723 if is_temp:
723 if is_temp:
724 try:
724 try:
725 return open(filename).read()
725 with open(filename) as f:
726 return f.read()
726 except IOError as msg:
727 except IOError as msg:
727 if msg.filename == filename:
728 if msg.filename == filename:
728 warn('File not found. Did you forget to save?')
729 warn('File not found. Did you forget to save?')
@@ -370,9 +370,8 b' python-profiler package from non-free.""")'
370 print('\n*** Profile stats marshalled to file',\
370 print('\n*** Profile stats marshalled to file',\
371 repr(dump_file)+'.',sys_exit)
371 repr(dump_file)+'.',sys_exit)
372 if text_file:
372 if text_file:
373 pfile = open(text_file,'w')
373 with open(text_file, 'w') as pfile:
374 pfile.write(output)
374 pfile.write(output)
375 pfile.close()
376 print('\n*** Profile printout saved to text file',\
375 print('\n*** Profile printout saved to text file',\
377 repr(text_file)+'.',sys_exit)
376 repr(text_file)+'.',sys_exit)
378
377
@@ -35,7 +35,8 b' def _get_conda_executable():'
35 # Otherwise, attempt to extract the executable from conda history.
35 # Otherwise, attempt to extract the executable from conda history.
36 # This applies in any conda environment.
36 # This applies in any conda environment.
37 R = re.compile(r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]")
37 R = re.compile(r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]")
38 for line in open(os.path.join(sys.prefix, 'conda-meta', 'history')):
38 with open(os.path.join(sys.prefix, 'conda-meta', 'history')) as f:
39 for line in f:
39 match = R.match(line)
40 match = R.match(line)
40 if match:
41 if match:
41 return match.groupdict()['command']
42 return match.groupdict()['command']
@@ -172,11 +172,11 b' class StoreMagics(Magics):'
172 fil = open(fnam, 'a')
172 fil = open(fnam, 'a')
173 else:
173 else:
174 fil = open(fnam, 'w')
174 fil = open(fnam, 'w')
175 with fil:
175 obj = ip.ev(args[0])
176 obj = ip.ev(args[0])
176 print("Writing '%s' (%s) to file '%s'." % (args[0],
177 print("Writing '%s' (%s) to file '%s'." % (args[0],
177 obj.__class__.__name__, fnam))
178 obj.__class__.__name__, fnam))
178
179
179
180 if not isinstance (obj, str):
180 if not isinstance (obj, str):
181 from pprint import pprint
181 from pprint import pprint
182 pprint(obj, fil)
182 pprint(obj, fil)
@@ -185,7 +185,6 b' class StoreMagics(Magics):'
185 if not obj.endswith('\n'):
185 if not obj.endswith('\n'):
186 fil.write('\n')
186 fil.write('\n')
187
187
188 fil.close()
189 return
188 return
190
189
191 # %store foo
190 # %store foo
@@ -109,19 +109,13 b' class Fixture(object):'
109 time.sleep(1.05)
109 time.sleep(1.05)
110
110
111 # Write
111 # Write
112 f = open(filename, 'w')
112 with open(filename, 'w') as f:
113 try:
114 f.write(content)
113 f.write(content)
115 finally:
116 f.close()
117
114
118 def new_module(self, code):
115 def new_module(self, code):
119 mod_name, mod_fn = self.get_module()
116 mod_name, mod_fn = self.get_module()
120 f = open(mod_fn, 'w')
117 with open(mod_fn, 'w') as f:
121 try:
122 f.write(code)
118 f.write(code)
123 finally:
124 f.close()
125 return mod_name, mod_fn
119 return mod_name, mod_fn
126
120
127 #-----------------------------------------------------------------------------
121 #-----------------------------------------------------------------------------
@@ -688,11 +688,8 b' class ExtensionDoctest(doctests.Doctest):'
688 else:
688 else:
689 if self.extension and anyp(filename.endswith, self.extension):
689 if self.extension and anyp(filename.endswith, self.extension):
690 name = os.path.basename(filename)
690 name = os.path.basename(filename)
691 dh = open(filename)
691 with open(filename) as dh:
692 try:
693 doc = dh.read()
692 doc = dh.read()
694 finally:
695 dh.close()
696 test = self.parser.get_doctest(
693 test = self.parser.get_doctest(
697 doc, globs={'__file__': filename}, name=name,
694 doc, globs={'__file__': filename}, name=name,
698 filename=filename, lineno=0)
695 filename=filename, lineno=0)
@@ -422,8 +422,7 b' def mute_warn():'
422 def make_tempfile(name):
422 def make_tempfile(name):
423 """ Create an empty, named, temporary file for the duration of the context.
423 """ Create an empty, named, temporary file for the duration of the context.
424 """
424 """
425 f = open(name, 'w')
425 open(name, 'w').close()
426 f.close()
427 try:
426 try:
428 yield
427 yield
429 finally:
428 finally:
@@ -37,8 +37,7 b" TMP_TEST_DIR = tempfile.mkdtemp(suffix='with.dot')"
37 old_syspath = sys.path
37 old_syspath = sys.path
38
38
39 def make_empty_file(fname):
39 def make_empty_file(fname):
40 f = open(fname, 'w')
40 open(fname, 'w').close()
41 f.close()
42
41
43
42
44 def setup():
43 def setup():
@@ -8,7 +8,7 b' mydir = os.path.dirname(__file__)'
8 nonascii_path = os.path.join(mydir, '../../core/tests/nonascii.py')
8 nonascii_path = os.path.join(mydir, '../../core/tests/nonascii.py')
9
9
10 def test_detect_encoding():
10 def test_detect_encoding():
11 f = open(nonascii_path, 'rb')
11 with open(nonascii_path, 'rb') as f:
12 enc, lines = openpy.detect_encoding(f.readline)
12 enc, lines = openpy.detect_encoding(f.readline)
13 nt.assert_equal(enc, 'iso-8859-5')
13 nt.assert_equal(enc, 'iso-8859-5')
14
14
@@ -392,9 +392,8 b' class ApiDocWriter(object):'
392 # write out to file
392 # write out to file
393 outfile = os.path.join(outdir,
393 outfile = os.path.join(outdir,
394 m + self.rst_extension)
394 m + self.rst_extension)
395 fileobj = open(outfile, 'wt')
395 with open(outfile, 'wt') as fileobj:
396 fileobj.write(api_str)
396 fileobj.write(api_str)
397 fileobj.close()
398 written_modules.append(m)
397 written_modules.append(m)
399 self.written_modules = written_modules
398 self.written_modules = written_modules
400
399
@@ -445,11 +444,10 b' class ApiDocWriter(object):'
445 relpath = outdir.replace(relative_to + os.path.sep, '')
444 relpath = outdir.replace(relative_to + os.path.sep, '')
446 else:
445 else:
447 relpath = outdir
446 relpath = outdir
448 idx = open(path,'wt')
447 with open(path,'wt') as idx:
449 w = idx.write
448 w = idx.write
450 w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
449 w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
451 w('.. autosummary::\n'
450 w('.. autosummary::\n'
452 ' :toctree: %s\n\n' % relpath)
451 ' :toctree: %s\n\n' % relpath)
453 for mod in self.written_modules:
452 for mod in self.written_modules:
454 w(' %s\n' % mod)
453 w(' %s\n' % mod)
455 idx.close()
@@ -3023,7 +3023,8 b''
3023 "source": [
3023 "source": [
3024 "from IPython.display import HTML\n",
3024 "from IPython.display import HTML\n",
3025 "from base64 import b64encode\n",
3025 "from base64 import b64encode\n",
3026 "video = open(\"../images/animation.m4v\", \"rb\").read()\n",
3026 "with open(\"../images/animation.m4v\", \"rb\") as f:\n",
3027 " video = f.read()\n",
3027 "video_encoded = b64encode(video).decode('ascii')\n",
3028 "video_encoded = b64encode(video).decode('ascii')\n",
3028 "video_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\n",
3029 "video_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\n",
3029 "HTML(data=video_tag)"
3030 "HTML(data=video_tag)"
@@ -27,6 +27,8 b' if len(sys.argv) > 2:'
27 else:
27 else:
28 dest = sys.stdout
28 dest = sys.stdout
29 raw = True
29 raw = True
30
31 with dest:
30 dest.write("# coding: utf-8\n")
32 dest.write("# coding: utf-8\n")
31
33
32 # Profiles other than 'default' can be specified here with a profile= argument:
34 # Profiles other than 'default' can be specified here with a profile= argument:
General Comments 0
You need to be logged in to leave comments. Login now