##// END OF EJS Templates
Format code
gousaiyang -
Show More
@@ -470,7 +470,7 b' class BaseIPythonApplication(Application):'
470 config_file = Path(self.profile_dir.location) / self.config_file_name
470 config_file = Path(self.profile_dir.location) / self.config_file_name
471 if self.overwrite or not config_file.exists():
471 if self.overwrite or not config_file.exists():
472 self.log.warning("Generating default config file: %r" % (config_file))
472 self.log.warning("Generating default config file: %r" % (config_file))
473 config_file.write_text(s, encoding='utf-8')
473 config_file.write_text(s, encoding="utf-8")
474
474
475 @catch_config_error
475 @catch_config_error
476 def initialize(self, argv=None):
476 def initialize(self, argv=None):
@@ -185,7 +185,7 b' class CrashHandler(object):'
185
185
186 # and generate a complete report on disk
186 # and generate a complete report on disk
187 try:
187 try:
188 report = open(report_name, 'w', encoding='utf-8')
188 report = open(report_name, "w", encoding="utf-8")
189 except:
189 except:
190 print('Could not create crash report on disk.', file=sys.stderr)
190 print('Could not create crash report on disk.', file=sys.stderr)
191 return
191 return
@@ -349,7 +349,7 b' class DisplayObject(object):'
349 def reload(self):
349 def reload(self):
350 """Reload the raw data from file or URL."""
350 """Reload the raw data from file or URL."""
351 if self.filename is not None:
351 if self.filename is not None:
352 encoding = None if 'b' in self._read_flags else 'utf-8'
352 encoding = None if "b" in self._read_flags else "utf-8"
353 with open(self.filename, self._read_flags, encoding=encoding) as f:
353 with open(self.filename, self._read_flags, encoding=encoding) as f:
354 self.data = f.read()
354 self.data = f.read()
355 elif self.url is not None:
355 elif self.url is not None:
@@ -370,8 +370,11 b' class DisplayObject(object):'
370 if 'gzip' in response.headers['content-encoding']:
370 if 'gzip' in response.headers['content-encoding']:
371 import gzip
371 import gzip
372 from io import BytesIO
372 from io import BytesIO
373
373 # assume utf-8 if encoding is not specified
374 # assume utf-8 if encoding is not specified
374 with gzip.open(BytesIO(data), 'rt', encoding=encoding or 'utf-8') as fp:
375 with gzip.open(
376 BytesIO(data), "rt", encoding=encoding or "utf-8"
377 ) as fp:
375 encoding = None
378 encoding = None
376 data = fp.read()
379 data = fp.read()
377
380
@@ -2626,7 +2626,7 b' class InteractiveShell(SingletonConfigurable):'
2626
2626
2627 # Make sure we can open the file
2627 # Make sure we can open the file
2628 try:
2628 try:
2629 with fname.open('rb'):
2629 with fname.open("rb"):
2630 pass
2630 pass
2631 except:
2631 except:
2632 warn('Could not open file <%s> for safe execution.' % fname)
2632 warn('Could not open file <%s> for safe execution.' % fname)
@@ -2684,7 +2684,7 b' class InteractiveShell(SingletonConfigurable):'
2684
2684
2685 # Make sure we can open the file
2685 # Make sure we can open the file
2686 try:
2686 try:
2687 with fname.open('rb'):
2687 with fname.open("rb"):
2688 pass
2688 pass
2689 except:
2689 except:
2690 warn('Could not open file <%s> for safe execution.' % fname)
2690 warn('Could not open file <%s> for safe execution.' % fname)
@@ -2706,7 +2706,7 b' class InteractiveShell(SingletonConfigurable):'
2706 if cell.cell_type == 'code':
2706 if cell.cell_type == 'code':
2707 yield cell.source
2707 yield cell.source
2708 else:
2708 else:
2709 yield fname.read_text(encoding='utf-8')
2709 yield fname.read_text(encoding="utf-8")
2710
2710
2711 with prepended_to_syspath(dname):
2711 with prepended_to_syspath(dname):
2712 try:
2712 try:
@@ -3458,7 +3458,7 b' class InteractiveShell(SingletonConfigurable):'
3458 self.tempfiles.append(file_path)
3458 self.tempfiles.append(file_path)
3459
3459
3460 if data:
3460 if data:
3461 file_path.write_text(data, encoding='utf-8')
3461 file_path.write_text(data, encoding="utf-8")
3462 return filename
3462 return filename
3463
3463
3464 def ask_yes_no(self, prompt, default=None, interrupt=None):
3464 def ask_yes_no(self, prompt, default=None, interrupt=None):
@@ -538,7 +538,7 b' class CodeMagics(Magics):'
538 self.shell.hooks.editor(filename)
538 self.shell.hooks.editor(filename)
539
539
540 # and make a new macro object, to replace the old one
540 # and make a new macro object, to replace the old one
541 mvalue = Path(filename).read_text(encoding='utf-8')
541 mvalue = Path(filename).read_text(encoding="utf-8")
542 self.shell.user_ns[mname] = Macro(mvalue)
542 self.shell.user_ns[mname] = Macro(mvalue)
543
543
544 @skip_doctest
544 @skip_doctest
@@ -728,7 +728,7 b' class CodeMagics(Magics):'
728 # XXX TODO: should this be generalized for all string vars?
728 # XXX TODO: should this be generalized for all string vars?
729 # For now, this is special-cased to blocks created by cpaste
729 # For now, this is special-cased to blocks created by cpaste
730 if args.strip() == "pasted_block":
730 if args.strip() == "pasted_block":
731 self.shell.user_ns["pasted_block"] = filepath.read_text(encoding='utf-8')
731 self.shell.user_ns["pasted_block"] = filepath.read_text(encoding="utf-8")
732
732
733 if 'x' in opts: # -x prevents actual execution
733 if 'x' in opts: # -x prevents actual execution
734 print()
734 print()
@@ -736,9 +736,9 b' class CodeMagics(Magics):'
736 print('done. Executing edited code...')
736 print('done. Executing edited code...')
737 with preserve_keys(self.shell.user_ns, '__file__'):
737 with preserve_keys(self.shell.user_ns, '__file__'):
738 if not is_temp:
738 if not is_temp:
739 self.shell.user_ns['__file__'] = filename
739 self.shell.user_ns["__file__"] = filename
740 if 'r' in opts: # Untranslated IPython code
740 if "r" in opts: # Untranslated IPython code
741 source = filepath.read_text(encoding='utf-8')
741 source = filepath.read_text(encoding="utf-8")
742 self.shell.run_cell(source, store_history=False)
742 self.shell.run_cell(source, store_history=False)
743 else:
743 else:
744 self.shell.safe_execfile(filename, self.shell.user_ns,
744 self.shell.safe_execfile(filename, self.shell.user_ns,
@@ -746,7 +746,7 b' class CodeMagics(Magics):'
746
746
747 if is_temp:
747 if is_temp:
748 try:
748 try:
749 return filepath.read_text(encoding='utf-8')
749 return filepath.read_text(encoding="utf-8")
750 except IOError as msg:
750 except IOError as msg:
751 if Path(msg.filename) == filepath:
751 if Path(msg.filename) == filepath:
752 warn('File not found. Did you forget to save?')
752 warn('File not found. Did you forget to save?')
@@ -360,7 +360,7 b' class ExecutionMagics(Magics):'
360 if text_file:
360 if text_file:
361 pfile = Path(text_file)
361 pfile = Path(text_file)
362 pfile.touch(exist_ok=True)
362 pfile.touch(exist_ok=True)
363 pfile.write_text(output, encoding='utf-8')
363 pfile.write_text(output, encoding="utf-8")
364
364
365 print(
365 print(
366 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
366 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
@@ -32,7 +32,7 b' def _get_conda_executable():'
32
32
33 # Otherwise, attempt to extract the executable from conda history.
33 # Otherwise, attempt to extract the executable from conda history.
34 # This applies in any conda environment.
34 # This applies in any conda environment.
35 history = Path(sys.prefix, "conda-meta", "history").read_text(encoding='utf-8')
35 history = Path(sys.prefix, "conda-meta", "history").read_text(encoding="utf-8")
36 match = re.search(
36 match = re.search(
37 r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]",
37 r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]",
38 history,
38 history,
@@ -199,7 +199,7 b' def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):'
199 tmppath = Path(tmpname)
199 tmppath = Path(tmpname)
200 try:
200 try:
201 os.close(fd)
201 os.close(fd)
202 with tmppath.open("wt", encoding='utf-8') as tmpfile:
202 with tmppath.open("wt", encoding="utf-8") as tmpfile:
203 tmpfile.write(strng)
203 tmpfile.write(strng)
204 cmd = "%s < %s" % (pager_cmd, tmppath)
204 cmd = "%s < %s" % (pager_cmd, tmppath)
205 # tmpfile needs to be closed for windows
205 # tmpfile needs to be closed for windows
@@ -213,12 +213,15 b' def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):'
213 try:
213 try:
214 retval = None
214 retval = None
215 # Emulate os.popen, but redirect stderr
215 # Emulate os.popen, but redirect stderr
216 proc = subprocess.Popen(pager_cmd,
216 proc = subprocess.Popen(
217 shell=True,
217 pager_cmd,
218 stdin=subprocess.PIPE,
218 shell=True,
219 stderr=subprocess.DEVNULL
219 stdin=subprocess.PIPE,
220 )
220 stderr=subprocess.DEVNULL,
221 pager = os._wrap_close(io.TextIOWrapper(proc.stdin, encoding='utf-8'), proc)
221 )
222 pager = os._wrap_close(
223 io.TextIOWrapper(proc.stdin, encoding="utf-8"), proc
224 )
222 try:
225 try:
223 pager_encoding = pager.encoding or sys.stdout.encoding
226 pager_encoding = pager.encoding or sys.stdout.encoding
224 pager.write(strng)
227 pager.write(strng)
@@ -277,7 +280,7 b' def page_file(fname, start=0, pager_cmd=None):'
277 try:
280 try:
278 if start > 0:
281 if start > 0:
279 start -= 1
282 start -= 1
280 page(open(fname, encoding='utf-8').read(),start)
283 page(open(fname, encoding="utf-8").read(), start)
281 except:
284 except:
282 print('Unable to show file',repr(fname))
285 print('Unable to show file',repr(fname))
283
286
@@ -34,7 +34,7 b' def test_unicode_ipdir():'
34 ipdir = tempfile.mkdtemp(suffix=u"€")
34 ipdir = tempfile.mkdtemp(suffix=u"€")
35
35
36 # Create the config file, so it tries to load it.
36 # Create the config file, so it tries to load it.
37 with open(os.path.join(ipdir, 'ipython_config.py'), "w", encoding='utf-8') as f:
37 with open(os.path.join(ipdir, "ipython_config.py"), "w", encoding="utf-8") as f:
38 pass
38 pass
39
39
40 old_ipdir1 = os.environ.pop("IPYTHONDIR", None)
40 old_ipdir1 = os.environ.pop("IPYTHONDIR", None)
@@ -59,7 +59,7 b' def test_cli_priority():'
59 test = Unicode().tag(config=True)
59 test = Unicode().tag(config=True)
60
60
61 # Create the config file, so it tries to load it.
61 # Create the config file, so it tries to load it.
62 with open(os.path.join(td, 'ipython_config.py'), "w", encoding='utf-8') as f:
62 with open(os.path.join(td, "ipython_config.py"), "w", encoding="utf-8") as f:
63 f.write("c.TestApp.test = 'config file'")
63 f.write("c.TestApp.test = 'config file'")
64
64
65 app = TestApp()
65 app = TestApp()
@@ -346,7 +346,7 b' class TestCompleter(unittest.TestCase):'
346 suffixes = ["1", "2"]
346 suffixes = ["1", "2"]
347 names = [prefix + s for s in suffixes]
347 names = [prefix + s for s in suffixes]
348 for n in names:
348 for n in names:
349 open(n, "w", encoding='utf-8').close()
349 open(n, "w", encoding="utf-8").close()
350
350
351 # Check simple completion
351 # Check simple completion
352 c = ip.complete(prefix)[1]
352 c = ip.complete(prefix)[1]
@@ -365,7 +365,7 b' class TestCompleter(unittest.TestCase):'
365 suffixes = ["1", "2"]
365 suffixes = ["1", "2"]
366 names = [prefix + s for s in suffixes]
366 names = [prefix + s for s in suffixes]
367 for n in names:
367 for n in names:
368 open(n, "w", encoding='utf-8').close()
368 open(n, "w", encoding="utf-8").close()
369
369
370 # Check simple completion
370 # Check simple completion
371 c = ip.complete(prefix)[1]
371 c = ip.complete(prefix)[1]
@@ -381,7 +381,7 b' class TestCompleter(unittest.TestCase):'
381 ip = get_ipython()
381 ip = get_ipython()
382 with TemporaryWorkingDirectory():
382 with TemporaryWorkingDirectory():
383 name = "foo'bar"
383 name = "foo'bar"
384 open(name, "w", encoding='utf-8').close()
384 open(name, "w", encoding="utf-8").close()
385
385
386 # Don't escape Windows
386 # Don't escape Windows
387 escaped = name if sys.platform == "win32" else "foo\\'bar"
387 escaped = name if sys.platform == "win32" else "foo\\'bar"
@@ -33,7 +33,7 b' class Test_magic_run_completer(unittest.TestCase):'
33 def setUp(self):
33 def setUp(self):
34 self.BASETESTDIR = tempfile.mkdtemp()
34 self.BASETESTDIR = tempfile.mkdtemp()
35 for fil in self.files:
35 for fil in self.files:
36 with open(join(self.BASETESTDIR, fil), "w", encoding='utf-8') as sfile:
36 with open(join(self.BASETESTDIR, fil), "w", encoding="utf-8") as sfile:
37 sfile.write("pass\n")
37 sfile.write("pass\n")
38 for d in self.dirs:
38 for d in self.dirs:
39 os.mkdir(join(self.BASETESTDIR, d))
39 os.mkdir(join(self.BASETESTDIR, d))
@@ -89,7 +89,7 b' class Test_magic_run_completer_nonascii(unittest.TestCase):'
89 def setUp(self):
89 def setUp(self):
90 self.BASETESTDIR = tempfile.mkdtemp()
90 self.BASETESTDIR = tempfile.mkdtemp()
91 for fil in [u"aaø.py", u"a.py", u"b.py"]:
91 for fil in [u"aaø.py", u"a.py", u"b.py"]:
92 with open(join(self.BASETESTDIR, fil), "w", encoding='utf-8') as sfile:
92 with open(join(self.BASETESTDIR, fil), "w", encoding="utf-8") as sfile:
93 sfile.write("pass\n")
93 sfile.write("pass\n")
94 self.oldpath = os.getcwd()
94 self.oldpath = os.getcwd()
95 os.chdir(self.BASETESTDIR)
95 os.chdir(self.BASETESTDIR)
@@ -133,8 +133,8 b' def test_import_invalid_module():'
133 with TemporaryDirectory() as tmpdir:
133 with TemporaryDirectory() as tmpdir:
134 sys.path.insert( 0, tmpdir )
134 sys.path.insert( 0, tmpdir )
135 for name in invalid_module_names | valid_module_names:
135 for name in invalid_module_names | valid_module_names:
136 filename = os.path.join(tmpdir, name + '.py')
136 filename = os.path.join(tmpdir, name + ".py")
137 open(filename, 'w', encoding='utf-8').close()
137 open(filename, "w", encoding="utf-8").close()
138
138
139 s = set( module_completion('import foo') )
139 s = set( module_completion('import foo') )
140 intersection = s.intersection(invalid_module_names)
140 intersection = s.intersection(invalid_module_names)
@@ -26,12 +26,12 b' def load_ipython_extension(ip):'
26 def test_extension_loading():
26 def test_extension_loading():
27 em = get_ipython().extension_manager
27 em = get_ipython().extension_manager
28 with TemporaryDirectory() as td:
28 with TemporaryDirectory() as td:
29 ext1 = os.path.join(td, 'ext1.py')
29 ext1 = os.path.join(td, "ext1.py")
30 with open(ext1, 'w', encoding='utf-8') as f:
30 with open(ext1, "w", encoding="utf-8") as f:
31 f.write(ext1_content)
31 f.write(ext1_content)
32
32
33 ext2 = os.path.join(td, 'ext2.py')
33 ext2 = os.path.join(td, "ext2.py")
34 with open(ext2, 'w', encoding='utf-8') as f:
34 with open(ext2, "w", encoding="utf-8") as f:
35 f.write(ext2_content)
35 f.write(ext2_content)
36
36
37 with prepended_to_syspath(td):
37 with prepended_to_syspath(td):
@@ -76,8 +76,8 b' def test_extension_loading():'
76 def test_extension_builtins():
76 def test_extension_builtins():
77 em = get_ipython().extension_manager
77 em = get_ipython().extension_manager
78 with TemporaryDirectory() as td:
78 with TemporaryDirectory() as td:
79 ext3 = os.path.join(td, 'ext3.py')
79 ext3 = os.path.join(td, "ext3.py")
80 with open(ext3, 'w', encoding='utf-8') as f:
80 with open(ext3, "w", encoding="utf-8") as f:
81 f.write(ext3_content)
81 f.write(ext3_content)
82
82
83 assert 'ext3' not in em.loaded
83 assert 'ext3' not in em.loaded
@@ -485,12 +485,12 b' class InteractiveShellTestCase(unittest.TestCase):'
485 def test_mktempfile(self):
485 def test_mktempfile(self):
486 filename = ip.mktempfile()
486 filename = ip.mktempfile()
487 # Check that we can open the file again on Windows
487 # Check that we can open the file again on Windows
488 with open(filename, 'w', encoding='utf-8') as f:
488 with open(filename, "w", encoding="utf-8") as f:
489 f.write('abc')
489 f.write("abc")
490
490
491 filename = ip.mktempfile(data='blah')
491 filename = ip.mktempfile(data="blah")
492 with open(filename, 'r', encoding='utf-8') as f:
492 with open(filename, "r", encoding="utf-8") as f:
493 self.assertEqual(f.read(), 'blah')
493 self.assertEqual(f.read(), "blah")
494
494
495 def test_new_main_mod(self):
495 def test_new_main_mod(self):
496 # Smoketest to check that this accepts a unicode module name
496 # Smoketest to check that this accepts a unicode module name
@@ -545,7 +545,9 b' class TestSafeExecfileNonAsciiPath(unittest.TestCase):'
545 self.BASETESTDIR = tempfile.mkdtemp()
545 self.BASETESTDIR = tempfile.mkdtemp()
546 self.TESTDIR = join(self.BASETESTDIR, u"åäö")
546 self.TESTDIR = join(self.BASETESTDIR, u"åäö")
547 os.mkdir(self.TESTDIR)
547 os.mkdir(self.TESTDIR)
548 with open(join(self.TESTDIR, u"åäötestscript.py"), "w", encoding='utf-8') as sfile:
548 with open(
549 join(self.TESTDIR, u"åäötestscript.py"), "w", encoding="utf-8"
550 ) as sfile:
549 sfile.write("pass\n")
551 sfile.write("pass\n")
550 self.oldpath = os.getcwd()
552 self.oldpath = os.getcwd()
551 os.chdir(self.TESTDIR)
553 os.chdir(self.TESTDIR)
@@ -861,12 +861,18 b' def test_file():'
861 """Basic %%writefile"""
861 """Basic %%writefile"""
862 ip = get_ipython()
862 ip = get_ipython()
863 with TemporaryDirectory() as td:
863 with TemporaryDirectory() as td:
864 fname = os.path.join(td, 'file1')
864 fname = os.path.join(td, "file1")
865 ip.run_cell_magic("writefile", fname, u'\n'.join([
865 ip.run_cell_magic(
866 'line1',
866 "writefile",
867 'line2',
867 fname,
868 ]))
868 "\n".join(
869 s = Path(fname).read_text(encoding='utf-8')
869 [
870 "line1",
871 "line2",
872 ]
873 ),
874 )
875 s = Path(fname).read_text(encoding="utf-8")
870 assert "line1\n" in s
876 assert "line1\n" in s
871 assert "line2" in s
877 assert "line2" in s
872
878
@@ -876,12 +882,18 b' def test_file_single_quote():'
876 """Basic %%writefile with embedded single quotes"""
882 """Basic %%writefile with embedded single quotes"""
877 ip = get_ipython()
883 ip = get_ipython()
878 with TemporaryDirectory() as td:
884 with TemporaryDirectory() as td:
879 fname = os.path.join(td, '\'file1\'')
885 fname = os.path.join(td, "'file1'")
880 ip.run_cell_magic("writefile", fname, u'\n'.join([
886 ip.run_cell_magic(
881 'line1',
887 "writefile",
882 'line2',
888 fname,
883 ]))
889 "\n".join(
884 s = Path(fname).read_text(encoding='utf-8')
890 [
891 "line1",
892 "line2",
893 ]
894 ),
895 )
896 s = Path(fname).read_text(encoding="utf-8")
885 assert "line1\n" in s
897 assert "line1\n" in s
886 assert "line2" in s
898 assert "line2" in s
887
899
@@ -892,11 +904,17 b' def test_file_double_quote():'
892 ip = get_ipython()
904 ip = get_ipython()
893 with TemporaryDirectory() as td:
905 with TemporaryDirectory() as td:
894 fname = os.path.join(td, '"file1"')
906 fname = os.path.join(td, '"file1"')
895 ip.run_cell_magic("writefile", fname, u'\n'.join([
907 ip.run_cell_magic(
896 'line1',
908 "writefile",
897 'line2',
909 fname,
898 ]))
910 "\n".join(
899 s = Path(fname).read_text(encoding='utf-8')
911 [
912 "line1",
913 "line2",
914 ]
915 ),
916 )
917 s = Path(fname).read_text(encoding="utf-8")
900 assert "line1\n" in s
918 assert "line1\n" in s
901 assert "line2" in s
919 assert "line2" in s
902
920
@@ -905,13 +923,19 b' def test_file_var_expand():'
905 """%%writefile $filename"""
923 """%%writefile $filename"""
906 ip = get_ipython()
924 ip = get_ipython()
907 with TemporaryDirectory() as td:
925 with TemporaryDirectory() as td:
908 fname = os.path.join(td, 'file1')
926 fname = os.path.join(td, "file1")
909 ip.user_ns['filename'] = fname
927 ip.user_ns["filename"] = fname
910 ip.run_cell_magic("writefile", '$filename', u'\n'.join([
928 ip.run_cell_magic(
911 'line1',
929 "writefile",
912 'line2',
930 "$filename",
913 ]))
931 "\n".join(
914 s = Path(fname).read_text(encoding='utf-8')
932 [
933 "line1",
934 "line2",
935 ]
936 ),
937 )
938 s = Path(fname).read_text(encoding="utf-8")
915 assert "line1\n" in s
939 assert "line1\n" in s
916 assert "line2" in s
940 assert "line2" in s
917
941
@@ -935,16 +959,28 b' def test_file_amend():'
935 """%%writefile -a amends files"""
959 """%%writefile -a amends files"""
936 ip = get_ipython()
960 ip = get_ipython()
937 with TemporaryDirectory() as td:
961 with TemporaryDirectory() as td:
938 fname = os.path.join(td, 'file2')
962 fname = os.path.join(td, "file2")
939 ip.run_cell_magic("writefile", fname, u'\n'.join([
963 ip.run_cell_magic(
940 'line1',
964 "writefile",
941 'line2',
965 fname,
942 ]))
966 "\n".join(
943 ip.run_cell_magic("writefile", "-a %s" % fname, u'\n'.join([
967 [
944 'line3',
968 "line1",
945 'line4',
969 "line2",
946 ]))
970 ]
947 s = Path(fname).read_text(encoding='utf-8')
971 ),
972 )
973 ip.run_cell_magic(
974 "writefile",
975 "-a %s" % fname,
976 "\n".join(
977 [
978 "line3",
979 "line4",
980 ]
981 ),
982 )
983 s = Path(fname).read_text(encoding="utf-8")
948 assert "line1\n" in s
984 assert "line1\n" in s
949 assert "line3\n" in s
985 assert "line3\n" in s
950
986
@@ -954,11 +990,17 b' def test_file_spaces():'
954 ip = get_ipython()
990 ip = get_ipython()
955 with TemporaryWorkingDirectory() as td:
991 with TemporaryWorkingDirectory() as td:
956 fname = "file name"
992 fname = "file name"
957 ip.run_cell_magic("file", '"%s"'%fname, u'\n'.join([
993 ip.run_cell_magic(
958 'line1',
994 "file",
959 'line2',
995 '"%s"' % fname,
960 ]))
996 "\n".join(
961 s = Path(fname).read_text(encoding='utf-8')
997 [
998 "line1",
999 "line2",
1000 ]
1001 ),
1002 )
1003 s = Path(fname).read_text(encoding="utf-8")
962 assert "line1\n" in s
1004 assert "line1\n" in s
963 assert "line2" in s
1005 assert "line2" in s
964
1006
@@ -1154,11 +1196,11 b' def test_save():'
1154 with TemporaryDirectory() as tmpdir:
1196 with TemporaryDirectory() as tmpdir:
1155 file = os.path.join(tmpdir, "testsave.py")
1197 file = os.path.join(tmpdir, "testsave.py")
1156 ip.run_line_magic("save", "%s 1-10" % file)
1198 ip.run_line_magic("save", "%s 1-10" % file)
1157 content = Path(file).read_text(encoding='utf-8')
1199 content = Path(file).read_text(encoding="utf-8")
1158 assert content.count(cmds[0]) == 1
1200 assert content.count(cmds[0]) == 1
1159 assert "coding: utf-8" in content
1201 assert "coding: utf-8" in content
1160 ip.run_line_magic("save", "-a %s 1-10" % file)
1202 ip.run_line_magic("save", "-a %s 1-10" % file)
1161 content = Path(file).read_text(encoding='utf-8')
1203 content = Path(file).read_text(encoding="utf-8")
1162 assert content.count(cmds[0]) == 2
1204 assert content.count(cmds[0]) == 2
1163 assert "coding: utf-8" in content
1205 assert "coding: utf-8" in content
1164
1206
@@ -1173,7 +1215,7 b' def test_save_with_no_args():'
1173 with TemporaryDirectory() as tmpdir:
1215 with TemporaryDirectory() as tmpdir:
1174 path = os.path.join(tmpdir, "testsave.py")
1216 path = os.path.join(tmpdir, "testsave.py")
1175 ip.run_line_magic("save", path)
1217 ip.run_line_magic("save", path)
1176 content = Path(path).read_text(encoding='utf-8')
1218 content = Path(path).read_text(encoding="utf-8")
1177 expected_content = dedent(
1219 expected_content = dedent(
1178 """\
1220 """\
1179 # coding: utf-8
1221 # coding: utf-8
@@ -1335,8 +1377,8 b' if __name__ == "__main__":'
1335 def test_run_module_from_import_hook():
1377 def test_run_module_from_import_hook():
1336 "Test that a module can be loaded via an import hook"
1378 "Test that a module can be loaded via an import hook"
1337 with TemporaryDirectory() as tmpdir:
1379 with TemporaryDirectory() as tmpdir:
1338 fullpath = os.path.join(tmpdir, 'my_tmp.py')
1380 fullpath = os.path.join(tmpdir, "my_tmp.py")
1339 Path(fullpath).write_text(TEST_MODULE, encoding='utf-8')
1381 Path(fullpath).write_text(TEST_MODULE, encoding="utf-8")
1340
1382
1341 import importlib.abc
1383 import importlib.abc
1342 import importlib.util
1384 import importlib.util
@@ -1352,7 +1394,7 b' def test_run_module_from_import_hook():'
1352
1394
1353 def get_data(self, path):
1395 def get_data(self, path):
1354 assert Path(path).samefile(fullpath)
1396 assert Path(path).samefile(fullpath)
1355 return Path(fullpath).read_text(encoding='utf-8')
1397 return Path(fullpath).read_text(encoding="utf-8")
1356
1398
1357 sys.meta_path.insert(0, MyTempImporter())
1399 sys.meta_path.insert(0, MyTempImporter())
1358
1400
@@ -84,10 +84,10 b' class ProfileStartupTest(TestCase):'
84
84
85 def init(self, startup_file, startup, test):
85 def init(self, startup_file, startup, test):
86 # write startup python file
86 # write startup python file
87 with open(Path(self.pd.startup_dir) / startup_file, "w", encoding='utf-8') as f:
87 with open(Path(self.pd.startup_dir) / startup_file, "w", encoding="utf-8") as f:
88 f.write(startup)
88 f.write(startup)
89 # write simple test file, to check that the startup file was run
89 # write simple test file, to check that the startup file was run
90 with open(self.fname, 'w', encoding='utf-8') as f:
90 with open(self.fname, "w", encoding="utf-8") as f:
91 f.write(test)
91 f.write(test)
92
92
93 def validate(self, output):
93 def validate(self, output):
@@ -111,7 +111,7 b' def test_list_profiles_in():'
111 if dec.unicode_paths:
111 if dec.unicode_paths:
112 Path(td / u"profile_ünicode").mkdir(parents=True)
112 Path(td / u"profile_ünicode").mkdir(parents=True)
113
113
114 with open(td / "profile_file", "w", encoding='utf-8') as f:
114 with open(td / "profile_file", "w", encoding="utf-8") as f:
115 f.write("I am not a profile directory")
115 f.write("I am not a profile directory")
116 profiles = list_profiles_in(td)
116 profiles = list_profiles_in(td)
117
117
@@ -443,7 +443,7 b' class TestMagicRunWithPackage(unittest.TestCase):'
443 d = os.path.dirname(path)
443 d = os.path.dirname(path)
444 if not os.path.isdir(d):
444 if not os.path.isdir(d):
445 os.makedirs(d)
445 os.makedirs(d)
446 with open(path, 'w', encoding='utf-8') as f:
446 with open(path, "w", encoding="utf-8") as f:
447 f.write(textwrap.dedent(content))
447 f.write(textwrap.dedent(content))
448
448
449 def setUp(self):
449 def setUp(self):
@@ -526,8 +526,8 b' class TestMagicRunWithPackage(unittest.TestCase):'
526
526
527 def test_run__name__():
527 def test_run__name__():
528 with TemporaryDirectory() as td:
528 with TemporaryDirectory() as td:
529 path = pjoin(td, 'foo.py')
529 path = pjoin(td, "foo.py")
530 with open(path, 'w', encoding='utf-8') as f:
530 with open(path, "w", encoding="utf-8") as f:
531 f.write("q = __name__")
531 f.write("q = __name__")
532
532
533 _ip.user_ns.pop("q", None)
533 _ip.user_ns.pop("q", None)
@@ -547,15 +547,19 b' def test_run__name__():'
547 def test_run_tb():
547 def test_run_tb():
548 """Test traceback offset in %run"""
548 """Test traceback offset in %run"""
549 with TemporaryDirectory() as td:
549 with TemporaryDirectory() as td:
550 path = pjoin(td, 'foo.py')
550 path = pjoin(td, "foo.py")
551 with open(path, 'w', encoding='utf-8') as f:
551 with open(path, "w", encoding="utf-8") as f:
552 f.write('\n'.join([
552 f.write(
553 "def foo():",
553 "\n".join(
554 " return bar()",
554 [
555 "def bar():",
555 "def foo():",
556 " raise RuntimeError('hello!')",
556 " return bar()",
557 "foo()",
557 "def bar():",
558 ]))
558 " raise RuntimeError('hello!')",
559 "foo()",
560 ]
561 )
562 )
559 with capture_output() as io:
563 with capture_output() as io:
560 _ip.magic('run {}'.format(path))
564 _ip.magic('run {}'.format(path))
561 out = io.stdout
565 out = io.stdout
@@ -577,8 +581,8 b' def test_multiprocessing_run():'
577 mpm = sys.modules.get('__mp_main__')
581 mpm = sys.modules.get('__mp_main__')
578 sys.modules['__mp_main__'] = None
582 sys.modules['__mp_main__'] = None
579 try:
583 try:
580 path = pjoin(td, 'test.py')
584 path = pjoin(td, "test.py")
581 with open(path, 'w', encoding='utf-8') as f:
585 with open(path, "w", encoding="utf-8") as f:
582 f.write("import multiprocessing\nprint('hoy')")
586 f.write("import multiprocessing\nprint('hoy')")
583 with capture_output() as io:
587 with capture_output() as io:
584 _ip.run_line_magic('run', path)
588 _ip.run_line_magic('run', path)
@@ -597,15 +601,19 b' def test_multiprocessing_run():'
597 def test_script_tb():
601 def test_script_tb():
598 """Test traceback offset in `ipython script.py`"""
602 """Test traceback offset in `ipython script.py`"""
599 with TemporaryDirectory() as td:
603 with TemporaryDirectory() as td:
600 path = pjoin(td, 'foo.py')
604 path = pjoin(td, "foo.py")
601 with open(path, 'w', encoding='utf-8') as f:
605 with open(path, "w", encoding="utf-8") as f:
602 f.write('\n'.join([
606 f.write(
603 "def foo():",
607 "\n".join(
604 " return bar()",
608 [
605 "def bar():",
609 "def foo():",
606 " raise RuntimeError('hello!')",
610 " return bar()",
607 "foo()",
611 "def bar():",
608 ]))
612 " raise RuntimeError('hello!')",
613 "foo()",
614 ]
615 )
616 )
609 out, err = tt.ipexec(path)
617 out, err = tt.ipexec(path)
610 assert "execfile" not in out
618 assert "execfile" not in out
611 assert "RuntimeError" in out
619 assert "RuntimeError" in out
@@ -58,7 +58,7 b' class ChangedPyFileTest(unittest.TestCase):'
58 """
58 """
59 with TemporaryDirectory() as td:
59 with TemporaryDirectory() as td:
60 fname = os.path.join(td, "foo.py")
60 fname = os.path.join(td, "foo.py")
61 with open(fname, "w", encoding='utf-8') as f:
61 with open(fname, "w", encoding="utf-8") as f:
62 f.write(file_1)
62 f.write(file_1)
63
63
64 with prepended_to_syspath(td):
64 with prepended_to_syspath(td):
@@ -68,7 +68,7 b' class ChangedPyFileTest(unittest.TestCase):'
68 ip.run_cell("foo.f()")
68 ip.run_cell("foo.f()")
69
69
70 # Make the file shorter, so the line of the error is missing.
70 # Make the file shorter, so the line of the error is missing.
71 with open(fname, "w", encoding='utf-8') as f:
71 with open(fname, "w", encoding="utf-8") as f:
72 f.write(file_2)
72 f.write(file_2)
73
73
74 # For some reason, this was failing on the *second* call after
74 # For some reason, this was failing on the *second* call after
@@ -92,7 +92,7 b' class NonAsciiTest(unittest.TestCase):'
92 # Non-ascii directory name as well.
92 # Non-ascii directory name as well.
93 with TemporaryDirectory(suffix=u'é') as td:
93 with TemporaryDirectory(suffix=u'é') as td:
94 fname = os.path.join(td, u"fooé.py")
94 fname = os.path.join(td, u"fooé.py")
95 with open(fname, "w", encoding='utf-8') as f:
95 with open(fname, "w", encoding="utf-8") as f:
96 f.write(file_1)
96 f.write(file_1)
97
97
98 with prepended_to_syspath(td):
98 with prepended_to_syspath(td):
@@ -172,7 +172,7 b' class IndentationErrorTest(unittest.TestCase):'
172
172
173 with TemporaryDirectory() as td:
173 with TemporaryDirectory() as td:
174 fname = os.path.join(td, "foo.py")
174 fname = os.path.join(td, "foo.py")
175 with open(fname, "w", encoding='utf-8') as f:
175 with open(fname, "w", encoding="utf-8") as f:
176 f.write(indentationerror_file)
176 f.write(indentationerror_file)
177
177
178 with tt.AssertPrints("IndentationError"):
178 with tt.AssertPrints("IndentationError"):
@@ -221,14 +221,14 b' bar()'
221 def test_changing_py_file(self):
221 def test_changing_py_file(self):
222 with TemporaryDirectory() as td:
222 with TemporaryDirectory() as td:
223 fname = os.path.join(td, "foo.py")
223 fname = os.path.join(td, "foo.py")
224 with open(fname, 'w', encoding='utf-8') as f:
224 with open(fname, "w", encoding="utf-8") as f:
225 f.write(se_file_1)
225 f.write(se_file_1)
226
226
227 with tt.AssertPrints(["7/", "SyntaxError"]):
227 with tt.AssertPrints(["7/", "SyntaxError"]):
228 ip.magic("run " + fname)
228 ip.magic("run " + fname)
229
229
230 # Modify the file
230 # Modify the file
231 with open(fname, 'w', encoding='utf-8') as f:
231 with open(fname, "w", encoding="utf-8") as f:
232 f.write(se_file_2)
232 f.write(se_file_2)
233
233
234 # The SyntaxError should point to the correct line
234 # The SyntaxError should point to the correct line
@@ -176,12 +176,12 b' class StoreMagics(Magics):'
176 # default action - store the variable
176 # default action - store the variable
177 else:
177 else:
178 # %store foo >file.txt or >>file.txt
178 # %store foo >file.txt or >>file.txt
179 if len(args) > 1 and args[1].startswith('>'):
179 if len(args) > 1 and args[1].startswith(">"):
180 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
180 fnam = os.path.expanduser(args[1].lstrip(">").lstrip())
181 if args[1].startswith('>>'):
181 if args[1].startswith(">>"):
182 fil = open(fnam, 'a', encoding='utf-8')
182 fil = open(fnam, "a", encoding="utf-8")
183 else:
183 else:
184 fil = open(fnam, 'w', encoding='utf-8')
184 fil = open(fnam, "w", encoding="utf-8")
185 with fil:
185 with fil:
186 obj = ip.ev(args[0])
186 obj = ip.ev(args[0])
187 print("Writing '%s' (%s) to file '%s'." % (args[0],
187 print("Writing '%s' (%s) to file '%s'." % (args[0],
@@ -119,13 +119,13 b' class Fixture(TestCase):'
119 time.sleep(1.05)
119 time.sleep(1.05)
120
120
121 # Write
121 # Write
122 with open(filename, "w", encoding='utf-8') as f:
122 with open(filename, "w", encoding="utf-8") as f:
123 f.write(content)
123 f.write(content)
124
124
125 def new_module(self, code):
125 def new_module(self, code):
126 code = textwrap.dedent(code)
126 code = textwrap.dedent(code)
127 mod_name, mod_fn = self.get_module()
127 mod_name, mod_fn = self.get_module()
128 with open(mod_fn, "w", encoding='utf-8') as f:
128 with open(mod_fn, "w", encoding="utf-8") as f:
129 f.write(code)
129 f.write(code)
130 return mod_name, mod_fn
130 return mod_name, mod_fn
131
131
@@ -405,7 +405,7 b' class Demo(object):'
405
405
406 filename = self.shell.mktempfile(self.src_blocks[index])
406 filename = self.shell.mktempfile(self.src_blocks[index])
407 self.shell.hooks.editor(filename, 1)
407 self.shell.hooks.editor(filename, 1)
408 with open(Path(filename), "r", encoding='utf-8') as f:
408 with open(Path(filename), "r", encoding="utf-8") as f:
409 new_block = f.read()
409 new_block = f.read()
410 # update the source and colored block
410 # update the source and colored block
411 self.src_blocks[index] = new_block
411 self.src_blocks[index] = new_block
@@ -19,9 +19,9 b' def test_deepreload():'
19 with TemporaryDirectory() as tmpdir:
19 with TemporaryDirectory() as tmpdir:
20 with prepended_to_syspath(tmpdir):
20 with prepended_to_syspath(tmpdir):
21 tmpdirpath = Path(tmpdir)
21 tmpdirpath = Path(tmpdir)
22 with open(tmpdirpath / "A.py", "w", encoding='utf-8') as f:
22 with open(tmpdirpath / "A.py", "w", encoding="utf-8") as f:
23 f.write("class Object:\n pass\nok = True\n")
23 f.write("class Object:\n pass\nok = True\n")
24 with open(tmpdirpath / "B.py", "w", encoding='utf-8') as f:
24 with open(tmpdirpath / "B.py", "w", encoding="utf-8") as f:
25 f.write("import A\nassert A.ok, 'we are fine'\n")
25 f.write("import A\nassert A.ok, 'we are fine'\n")
26 import A
26 import A
27 import B
27 import B
@@ -62,7 +62,7 b' def test_temp_pyfile():'
62 src = 'pass\n'
62 src = 'pass\n'
63 fname = tt.temp_pyfile(src)
63 fname = tt.temp_pyfile(src)
64 assert os.path.isfile(fname)
64 assert os.path.isfile(fname)
65 with open(fname, encoding='utf-8') as fh2:
65 with open(fname, encoding="utf-8") as fh2:
66 src2 = fh2.read()
66 src2 = fh2.read()
67 assert src2 == src
67 assert src2 == src
68
68
@@ -426,9 +426,8 b' def mute_warn():'
426
426
427 @contextmanager
427 @contextmanager
428 def make_tempfile(name):
428 def make_tempfile(name):
429 """ Create an empty, named, temporary file for the duration of the context.
429 """Create an empty, named, temporary file for the duration of the context."""
430 """
430 open(name, "w", encoding="utf-8").close()
431 open(name, 'w', encoding='utf-8').close()
432 try:
431 try:
433 yield
432 yield
434 finally:
433 finally:
@@ -33,7 +33,9 b' def test_cve_2022_21699():'
33
33
34 with TemporaryWorkingDirectory() as t:
34 with TemporaryWorkingDirectory() as t:
35 dangerous_startup_dir.mkdir(parents=True)
35 dangerous_startup_dir.mkdir(parents=True)
36 (dangerous_startup_dir / "foo.py").write_text(f'print("{dangerous_expected}")', encoding='utf-8')
36 (dangerous_startup_dir / "foo.py").write_text(
37 f'print("{dangerous_expected}")', encoding="utf-8"
38 )
37 # 1 sec to make sure FS is flushed.
39 # 1 sec to make sure FS is flushed.
38 # time.sleep(1)
40 # time.sleep(1)
39 cmd = [sys.executable, "-m", "IPython"]
41 cmd = [sys.executable, "-m", "IPython"]
@@ -20,7 +20,7 b' from IPython.utils.decorators import undoc'
20 from .capture import CapturedIO, capture_output
20 from .capture import CapturedIO, capture_output
21
21
22 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
22 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
23 devnull = open(os.devnull, 'w', encoding='utf-8')
23 devnull = open(os.devnull, "w", encoding="utf-8")
24 atexit.register(devnull.close)
24 atexit.register(devnull.close)
25
25
26
26
@@ -52,7 +52,7 b' class Tee(object):'
52 if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
52 if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
53 self.file = file_or_name
53 self.file = file_or_name
54 else:
54 else:
55 encoding = None if 'b' in mode else 'utf-8'
55 encoding = None if "b" in mode else "utf-8"
56 self.file = open(file_or_name, mode, encoding=encoding)
56 self.file = open(file_or_name, mode, encoding=encoding)
57 self.channel = channel
57 self.channel = channel
58 self.ostream = getattr(sys, channel)
58 self.ostream = getattr(sys, channel)
@@ -132,7 +132,7 b" def temp_pyfile(src, ext='.py'):"
132 It is the caller's responsibility to close the open file and unlink it.
132 It is the caller's responsibility to close the open file and unlink it.
133 """
133 """
134 fname = tempfile.mkstemp(ext)[1]
134 fname = tempfile.mkstemp(ext)[1]
135 with open(Path(fname), "w", encoding='utf-8') as f:
135 with open(Path(fname), "w", encoding="utf-8") as f:
136 f.write(src)
136 f.write(src)
137 f.flush()
137 f.flush()
138 return fname
138 return fname
@@ -24,7 +24,7 b' class NamedFileInTemporaryDirectory(object):'
24 """
24 """
25 self._tmpdir = TemporaryDirectory(**kwds)
25 self._tmpdir = TemporaryDirectory(**kwds)
26 path = Path(self._tmpdir.name) / filename
26 path = Path(self._tmpdir.name) / filename
27 encoding = None if 'b' in mode else 'utf-8'
27 encoding = None if "b" in mode else "utf-8"
28 self.file = open(path, mode, bufsize, encoding=encoding)
28 self.file = open(path, mode, bufsize, encoding=encoding)
29
29
30 def cleanup(self):
30 def cleanup(self):
@@ -32,7 +32,7 b' TMP_TEST_DIR = Path(tempfile.mkdtemp(suffix="with.dot"))'
32 old_syspath = sys.path
32 old_syspath = sys.path
33
33
34 def make_empty_file(fname):
34 def make_empty_file(fname):
35 open(fname, 'w', encoding='utf-8').close()
35 open(fname, "w", encoding="utf-8").close()
36
36
37
37
38 def setup_module():
38 def setup_module():
@@ -295,7 +295,7 b' class TestRaiseDeprecation(unittest.TestCase):'
295 ipdir = os.path.join(tmpdir, '.ipython')
295 ipdir = os.path.join(tmpdir, '.ipython')
296 os.mkdir(ipdir, 0o555)
296 os.mkdir(ipdir, 0o555)
297 try:
297 try:
298 open(os.path.join(ipdir, "_foo_"), 'w', encoding='utf-8').close()
298 open(os.path.join(ipdir, "_foo_"), "w", encoding="utf-8").close()
299 except IOError:
299 except IOError:
300 pass
300 pass
301 else:
301 else:
@@ -352,7 +352,7 b' class TestShellGlob(unittest.TestCase):'
352 with cls.in_tempdir():
352 with cls.in_tempdir():
353 # Create empty files
353 # Create empty files
354 for fname in cls.filenames:
354 for fname in cls.filenames:
355 open(os.path.join(td, fname), 'w', encoding='utf-8').close()
355 open(os.path.join(td, fname), "w", encoding="utf-8").close()
356
356
357 @classmethod
357 @classmethod
358 def tearDownClass(cls):
358 def tearDownClass(cls):
@@ -426,9 +426,9 b' def test_ensure_dir_exists():'
426 d = os.path.join(td, '∂ir')
426 d = os.path.join(td, '∂ir')
427 path.ensure_dir_exists(d) # create it
427 path.ensure_dir_exists(d) # create it
428 assert os.path.isdir(d)
428 assert os.path.isdir(d)
429 path.ensure_dir_exists(d) # no-op
429 path.ensure_dir_exists(d) # no-op
430 f = os.path.join(td, 'ƒile')
430 f = os.path.join(td, "ƒile")
431 open(f, 'w', encoding='utf-8').close() # touch
431 open(f, "w", encoding="utf-8").close() # touch
432 with pytest.raises(IOError):
432 with pytest.raises(IOError):
433 path.ensure_dir_exists(f)
433 path.ensure_dir_exists(f)
434
434
@@ -436,7 +436,7 b' class TestLinkOrCopy(unittest.TestCase):'
436 def setUp(self):
436 def setUp(self):
437 self.tempdir = TemporaryDirectory()
437 self.tempdir = TemporaryDirectory()
438 self.src = self.dst("src")
438 self.src = self.dst("src")
439 with open(self.src, "w", encoding='utf-8') as f:
439 with open(self.src, "w", encoding="utf-8") as f:
440 f.write("Hello, world!")
440 f.write("Hello, world!")
441
441
442 def tearDown(self):
442 def tearDown(self):
@@ -456,8 +456,8 b' class TestLinkOrCopy(unittest.TestCase):'
456 ), "%r and %r do not reference the same indoes" % (a, b)
456 ), "%r and %r do not reference the same indoes" % (a, b)
457
457
458 def assert_content_equal(self, a, b):
458 def assert_content_equal(self, a, b):
459 with open(a, 'rb') as a_f:
459 with open(a, "rb") as a_f:
460 with open(b, 'rb') as b_f:
460 with open(b, "rb") as b_f:
461 assert a_f.read() == b_f.read()
461 assert a_f.read() == b_f.read()
462
462
463 @skip_win32
463 @skip_win32
@@ -477,7 +477,7 b' class TestLinkOrCopy(unittest.TestCase):'
477 @skip_win32
477 @skip_win32
478 def test_target_exists(self):
478 def test_target_exists(self):
479 dst = self.dst("target")
479 dst = self.dst("target")
480 open(dst, "w", encoding='utf-8').close()
480 open(dst, "w", encoding="utf-8").close()
481 path.link_or_copy(self.src, dst)
481 path.link_or_copy(self.src, dst)
482 self.assert_inode_equal(self.src, dst)
482 self.assert_inode_equal(self.src, dst)
483
483
@@ -102,7 +102,7 b' def reverse_aliases(app):'
102 def write_doc(name, title, app, preamble=None):
102 def write_doc(name, title, app, preamble=None):
103 trait_aliases = reverse_aliases(app)
103 trait_aliases = reverse_aliases(app)
104 filename = options / (name + ".rst")
104 filename = options / (name + ".rst")
105 with open(filename, "w", encoding='utf-8') as f:
105 with open(filename, "w", encoding="utf-8") as f:
106 f.write(title + "\n")
106 f.write(title + "\n")
107 f.write(("=" * len(title)) + "\n")
107 f.write(("=" * len(title)) + "\n")
108 f.write("\n")
108 f.write("\n")
@@ -117,7 +117,7 b' def write_doc(name, title, app, preamble=None):'
117
117
118 if __name__ == '__main__':
118 if __name__ == '__main__':
119 # Touch this file for the make target
119 # Touch this file for the make target
120 Path(generated).write_text("", encoding='utf-8')
120 Path(generated).write_text("", encoding="utf-8")
121
121
122 write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp())
122 write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp())
123 write_doc('kernel', 'IPython kernel options', IPKernelApp(),
123 write_doc('kernel', 'IPython kernel options', IPKernelApp(),
@@ -63,4 +63,4 b' for name, func in sorted(magics["cell"].items(), key=sortkey):'
63
63
64 src_path = Path(__file__).parent
64 src_path = Path(__file__).parent
65 dest = src_path.joinpath("source", "interactive", "magics-generated.txt")
65 dest = src_path.joinpath("source", "interactive", "magics-generated.txt")
66 dest.write_text("\n".join(output), encoding='utf-8')
66 dest.write_text("\n".join(output), encoding="utf-8")
@@ -89,6 +89,8 b" if __name__ == '__main__':"
89 (single_filter, "single_filtered"),
89 (single_filter, "single_filtered"),
90 (multi_filter, "multi_filtered"),
90 (multi_filter, "multi_filtered"),
91 ]:
91 ]:
92 with (dest / "{}.csv".format(output_filename)).open("w", encoding='utf-8') as csv:
92 with (dest / "{}.csv".format(output_filename)).open(
93 "w", encoding="utf-8"
94 ) as csv:
93 for (shortcut, flt), v in sorted(filters.items(), key=sort_key):
95 for (shortcut, flt), v in sorted(filters.items(), key=sort_key):
94 csv.write(":kbd:`{}`\t{}\t{}\n".format(shortcut, flt, v))
96 csv.write(":kbd:`{}`\t{}\t{}\n".format(shortcut, flt, v))
@@ -28,11 +28,14 b' if ON_RTD:'
28 for name in ("config", "api", "magics", "shortcuts"):
28 for name in ("config", "api", "magics", "shortcuts"):
29 fname = Path("autogen_{}.py".format(name))
29 fname = Path("autogen_{}.py".format(name))
30 fpath = (Path(__file__).parent).joinpath("..", fname)
30 fpath = (Path(__file__).parent).joinpath("..", fname)
31 with open(fpath, encoding='utf-8') as f:
31 with open(fpath, encoding="utf-8") as f:
32 exec(compile(f.read(), fname, 'exec'), {
32 exec(
33 '__file__': fpath,
33 compile(f.read(), fname, "exec"),
34 '__name__': '__main__',
34 {
35 })
35 "__file__": fpath,
36 "__name__": "__main__",
37 },
38 )
36 else:
39 else:
37 import sphinx_rtd_theme
40 import sphinx_rtd_theme
38 html_theme = "sphinx_rtd_theme"
41 html_theme = "sphinx_rtd_theme"
@@ -45,7 +48,14 b" sys.path.insert(0, os.path.abspath('../sphinxext'))"
45
48
46 # We load the ipython release info into a dict by explicit execution
49 # We load the ipython release info into a dict by explicit execution
47 iprelease = {}
50 iprelease = {}
48 exec(compile(open('../../IPython/core/release.py', encoding='utf-8').read(), '../../IPython/core/release.py', 'exec'),iprelease)
51 exec(
52 compile(
53 open("../../IPython/core/release.py", encoding="utf-8").read(),
54 "../../IPython/core/release.py",
55 "exec",
56 ),
57 iprelease,
58 )
49
59
50 # General configuration
60 # General configuration
51 # ---------------------
61 # ---------------------
@@ -390,9 +390,8 b' class ApiDocWriter(object):'
390 if not api_str:
390 if not api_str:
391 continue
391 continue
392 # write out to file
392 # write out to file
393 outfile = os.path.join(outdir,
393 outfile = os.path.join(outdir, m + self.rst_extension)
394 m + self.rst_extension)
394 with open(outfile, "wt", encoding="utf-8") as fileobj:
395 with open(outfile, 'wt', encoding='utf-8') as fileobj:
396 fileobj.write(api_str)
395 fileobj.write(api_str)
397 written_modules.append(m)
396 written_modules.append(m)
398 self.written_modules = written_modules
397 self.written_modules = written_modules
@@ -444,7 +443,7 b' class ApiDocWriter(object):'
444 relpath = outdir.replace(relative_to + os.path.sep, '')
443 relpath = outdir.replace(relative_to + os.path.sep, '')
445 else:
444 else:
446 relpath = outdir
445 relpath = outdir
447 with open(path,'wt', encoding='utf-8') as idx:
446 with open(path, "wt", encoding="utf-8") as idx:
448 w = idx.write
447 w = idx.write
449 w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
448 w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
450 w('.. autosummary::\n'
449 w('.. autosummary::\n'
@@ -24,7 +24,7 b' from IPython.core.history import HistoryAccessor'
24 session_number = int(sys.argv[1])
24 session_number = int(sys.argv[1])
25 if len(sys.argv) > 2:
25 if len(sys.argv) > 2:
26 filepath = Path(sys.argv[2])
26 filepath = Path(sys.argv[2])
27 dest = open(filepath, "w", encoding='utf-8')
27 dest = open(filepath, "w", encoding="utf-8")
28 raw = not filepath.name.endswith(".py")
28 raw = not filepath.name.endswith(".py")
29 else:
29 else:
30 dest = sys.stdout
30 dest = sys.stdout
@@ -36,7 +36,7 b' repo_root = os.path.dirname(os.path.abspath(__file__))'
36
36
37 def execfile(fname, globs, locs=None):
37 def execfile(fname, globs, locs=None):
38 locs = locs or globs
38 locs = locs or globs
39 with open(fname, encoding='utf-8') as f:
39 with open(fname, encoding="utf-8") as f:
40 exec(compile(f.read(), fname, "exec"), globs, locs)
40 exec(compile(f.read(), fname, "exec"), globs, locs)
41
41
42 # A little utility we'll need below, since glob() does NOT allow you to do
42 # A little utility we'll need below, since glob() does NOT allow you to do
@@ -336,10 +336,13 b' def git_prebuild(pkg_dir, build_cmd=build_py):'
336 os.remove(out_pth)
336 os.remove(out_pth)
337 except (IOError, OSError):
337 except (IOError, OSError):
338 pass
338 pass
339 with open(out_pth, 'w', encoding='utf-8') as out_file:
339 with open(out_pth, "w", encoding="utf-8") as out_file:
340 out_file.writelines([
340 out_file.writelines(
341 '# GENERATED BY setup.py\n',
341 [
342 'commit = u"%s"\n' % repo_commit,
342 "# GENERATED BY setup.py\n",
343 ])
343 'commit = u"%s"\n' % repo_commit,
344 ]
345 )
346
344 return MyBuildPy
347 return MyBuildPy
345
348
@@ -22,14 +22,14 b' def main():'
22 print("Adding pseudo-title to:", filepath.name)
22 print("Adding pseudo-title to:", filepath.name)
23 title = filepath.name[:-4].split("/")[-1].replace("-", " ").capitalize()
23 title = filepath.name[:-4].split("/")[-1].replace("-", " ").capitalize()
24
24
25 data = filepath.read_text(encoding='utf-8')
25 data = filepath.read_text(encoding="utf-8")
26 try:
26 try:
27 if data and data.splitlines()[1].startswith('='):
27 if data and data.splitlines()[1].startswith('='):
28 continue
28 continue
29 except IndexError:
29 except IndexError:
30 pass
30 pass
31
31
32 with filepath.open("w", encoding='utf-8') as f:
32 with filepath.open("w", encoding="utf-8") as f:
33 f.write(title + "\n")
33 f.write(title + "\n")
34 f.write("=" * len(title) + "\n\n")
34 f.write("=" * len(title) + "\n\n")
35 f.write(data)
35 f.write(data)
@@ -45,4 +45,4 b' def get_ipdir():'
45
45
46 def execfile(fname, globs, locs=None):
46 def execfile(fname, globs, locs=None):
47 locs = locs or globs
47 locs = locs or globs
48 exec(compile(open(fname, encoding='utf-8').read(), fname, "exec"), globs, locs)
48 exec(compile(open(fname, encoding="utf-8").read(), fname, "exec"), globs, locs)
General Comments 0
You need to be logged in to leave comments. Login now