##// END OF EJS Templates
Merge pull request #13510 from gousaiyang/fix-3-10-encoding-warning...
Matthias Bussonnier -
r27514:0f4a73c9 merge
parent child Browse files
Show More
@@ -41,7 +41,7 b' jobs:'
41 python -m pip install --upgrade -e file://$PWD#egg=ipython[test]
41 python -m pip install --upgrade -e file://$PWD#egg=ipython[test]
42 # we must instal IPython after ipykernel to get the right versions.
42 # we must instal IPython after ipykernel to get the right versions.
43 python -m pip install --upgrade --upgrade-strategy eager flaky ipyparallel
43 python -m pip install --upgrade --upgrade-strategy eager flaky ipyparallel
44 python -m pip install --upgrade pytest
44 python -m pip install --upgrade 'pytest<7'
45 - name: pytest
45 - name: pytest
46 env:
46 env:
47 COLUMNS: 120
47 COLUMNS: 120
@@ -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)
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')
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,8 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 with open(self.filename, self._read_flags) as f:
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 self.data = f.read()
354 self.data = f.read()
354 elif self.url is not None:
355 elif self.url is not None:
355 # Deferred import
356 # Deferred import
@@ -369,7 +370,11 b' class DisplayObject(object):'
369 if 'gzip' in response.headers['content-encoding']:
370 if 'gzip' in response.headers['content-encoding']:
370 import gzip
371 import gzip
371 from io import BytesIO
372 from io import BytesIO
372 with gzip.open(BytesIO(data), 'rt', encoding=encoding) as fp:
373
374 # assume utf-8 if encoding is not specified
375 with gzip.open(
376 BytesIO(data), "rt", encoding=encoding or "utf-8"
377 ) as fp:
373 encoding = None
378 encoding = None
374 data = fp.read()
379 data = fp.read()
375
380
@@ -2667,7 +2667,7 b' class InteractiveShell(SingletonConfigurable):'
2667
2667
2668 # Make sure we can open the file
2668 # Make sure we can open the file
2669 try:
2669 try:
2670 with fname.open():
2670 with fname.open("rb"):
2671 pass
2671 pass
2672 except:
2672 except:
2673 warn('Could not open file <%s> for safe execution.' % fname)
2673 warn('Could not open file <%s> for safe execution.' % fname)
@@ -2725,7 +2725,7 b' class InteractiveShell(SingletonConfigurable):'
2725
2725
2726 # Make sure we can open the file
2726 # Make sure we can open the file
2727 try:
2727 try:
2728 with fname.open():
2728 with fname.open("rb"):
2729 pass
2729 pass
2730 except:
2730 except:
2731 warn('Could not open file <%s> for safe execution.' % fname)
2731 warn('Could not open file <%s> for safe execution.' % fname)
@@ -2747,7 +2747,7 b' class InteractiveShell(SingletonConfigurable):'
2747 if cell.cell_type == 'code':
2747 if cell.cell_type == 'code':
2748 yield cell.source
2748 yield cell.source
2749 else:
2749 else:
2750 yield fname.read_text()
2750 yield fname.read_text(encoding="utf-8")
2751
2751
2752 with prepended_to_syspath(dname):
2752 with prepended_to_syspath(dname):
2753 try:
2753 try:
@@ -3499,7 +3499,7 b' class InteractiveShell(SingletonConfigurable):'
3499 self.tempfiles.append(file_path)
3499 self.tempfiles.append(file_path)
3500
3500
3501 if data:
3501 if data:
3502 file_path.write_text(data)
3502 file_path.write_text(data, encoding="utf-8")
3503 return filename
3503 return filename
3504
3504
3505 def ask_yes_no(self, prompt, default=None, interrupt=None):
3505 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()
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()
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()
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()
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)
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()
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") 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), 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).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") 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") 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").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").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").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") 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") 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').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') 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') 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') 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') 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') 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") 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)
@@ -863,12 +863,18 b' def test_file():'
863 """Basic %%writefile"""
863 """Basic %%writefile"""
864 ip = get_ipython()
864 ip = get_ipython()
865 with TemporaryDirectory() as td:
865 with TemporaryDirectory() as td:
866 fname = os.path.join(td, 'file1')
866 fname = os.path.join(td, "file1")
867 ip.run_cell_magic("writefile", fname, u'\n'.join([
867 ip.run_cell_magic(
868 'line1',
868 "writefile",
869 'line2',
869 fname,
870 ]))
870 "\n".join(
871 s = Path(fname).read_text()
871 [
872 "line1",
873 "line2",
874 ]
875 ),
876 )
877 s = Path(fname).read_text(encoding="utf-8")
872 assert "line1\n" in s
878 assert "line1\n" in s
873 assert "line2" in s
879 assert "line2" in s
874
880
@@ -878,12 +884,18 b' def test_file_single_quote():'
878 """Basic %%writefile with embedded single quotes"""
884 """Basic %%writefile with embedded single quotes"""
879 ip = get_ipython()
885 ip = get_ipython()
880 with TemporaryDirectory() as td:
886 with TemporaryDirectory() as td:
881 fname = os.path.join(td, '\'file1\'')
887 fname = os.path.join(td, "'file1'")
882 ip.run_cell_magic("writefile", fname, u'\n'.join([
888 ip.run_cell_magic(
883 'line1',
889 "writefile",
884 'line2',
890 fname,
885 ]))
891 "\n".join(
886 s = Path(fname).read_text()
892 [
893 "line1",
894 "line2",
895 ]
896 ),
897 )
898 s = Path(fname).read_text(encoding="utf-8")
887 assert "line1\n" in s
899 assert "line1\n" in s
888 assert "line2" in s
900 assert "line2" in s
889
901
@@ -894,11 +906,17 b' def test_file_double_quote():'
894 ip = get_ipython()
906 ip = get_ipython()
895 with TemporaryDirectory() as td:
907 with TemporaryDirectory() as td:
896 fname = os.path.join(td, '"file1"')
908 fname = os.path.join(td, '"file1"')
897 ip.run_cell_magic("writefile", fname, u'\n'.join([
909 ip.run_cell_magic(
898 'line1',
910 "writefile",
899 'line2',
911 fname,
900 ]))
912 "\n".join(
901 s = Path(fname).read_text()
913 [
914 "line1",
915 "line2",
916 ]
917 ),
918 )
919 s = Path(fname).read_text(encoding="utf-8")
902 assert "line1\n" in s
920 assert "line1\n" in s
903 assert "line2" in s
921 assert "line2" in s
904
922
@@ -907,13 +925,19 b' def test_file_var_expand():'
907 """%%writefile $filename"""
925 """%%writefile $filename"""
908 ip = get_ipython()
926 ip = get_ipython()
909 with TemporaryDirectory() as td:
927 with TemporaryDirectory() as td:
910 fname = os.path.join(td, 'file1')
928 fname = os.path.join(td, "file1")
911 ip.user_ns['filename'] = fname
929 ip.user_ns["filename"] = fname
912 ip.run_cell_magic("writefile", '$filename', u'\n'.join([
930 ip.run_cell_magic(
913 'line1',
931 "writefile",
914 'line2',
932 "$filename",
915 ]))
933 "\n".join(
916 s = Path(fname).read_text()
934 [
935 "line1",
936 "line2",
937 ]
938 ),
939 )
940 s = Path(fname).read_text(encoding="utf-8")
917 assert "line1\n" in s
941 assert "line1\n" in s
918 assert "line2" in s
942 assert "line2" in s
919
943
@@ -937,16 +961,28 b' def test_file_amend():'
937 """%%writefile -a amends files"""
961 """%%writefile -a amends files"""
938 ip = get_ipython()
962 ip = get_ipython()
939 with TemporaryDirectory() as td:
963 with TemporaryDirectory() as td:
940 fname = os.path.join(td, 'file2')
964 fname = os.path.join(td, "file2")
941 ip.run_cell_magic("writefile", fname, u'\n'.join([
965 ip.run_cell_magic(
942 'line1',
966 "writefile",
943 'line2',
967 fname,
944 ]))
968 "\n".join(
945 ip.run_cell_magic("writefile", "-a %s" % fname, u'\n'.join([
969 [
946 'line3',
970 "line1",
947 'line4',
971 "line2",
948 ]))
972 ]
949 s = Path(fname).read_text()
973 ),
974 )
975 ip.run_cell_magic(
976 "writefile",
977 "-a %s" % fname,
978 "\n".join(
979 [
980 "line3",
981 "line4",
982 ]
983 ),
984 )
985 s = Path(fname).read_text(encoding="utf-8")
950 assert "line1\n" in s
986 assert "line1\n" in s
951 assert "line3\n" in s
987 assert "line3\n" in s
952
988
@@ -956,11 +992,17 b' def test_file_spaces():'
956 ip = get_ipython()
992 ip = get_ipython()
957 with TemporaryWorkingDirectory() as td:
993 with TemporaryWorkingDirectory() as td:
958 fname = "file name"
994 fname = "file name"
959 ip.run_cell_magic("file", '"%s"'%fname, u'\n'.join([
995 ip.run_cell_magic(
960 'line1',
996 "file",
961 'line2',
997 '"%s"' % fname,
962 ]))
998 "\n".join(
963 s = Path(fname).read_text()
999 [
1000 "line1",
1001 "line2",
1002 ]
1003 ),
1004 )
1005 s = Path(fname).read_text(encoding="utf-8")
964 assert "line1\n" in s
1006 assert "line1\n" in s
965 assert "line2" in s
1007 assert "line2" in s
966
1008
@@ -1156,11 +1198,11 b' def test_save():'
1156 with TemporaryDirectory() as tmpdir:
1198 with TemporaryDirectory() as tmpdir:
1157 file = os.path.join(tmpdir, "testsave.py")
1199 file = os.path.join(tmpdir, "testsave.py")
1158 ip.run_line_magic("save", "%s 1-10" % file)
1200 ip.run_line_magic("save", "%s 1-10" % file)
1159 content = Path(file).read_text()
1201 content = Path(file).read_text(encoding="utf-8")
1160 assert content.count(cmds[0]) == 1
1202 assert content.count(cmds[0]) == 1
1161 assert "coding: utf-8" in content
1203 assert "coding: utf-8" in content
1162 ip.run_line_magic("save", "-a %s 1-10" % file)
1204 ip.run_line_magic("save", "-a %s 1-10" % file)
1163 content = Path(file).read_text()
1205 content = Path(file).read_text(encoding="utf-8")
1164 assert content.count(cmds[0]) == 2
1206 assert content.count(cmds[0]) == 2
1165 assert "coding: utf-8" in content
1207 assert "coding: utf-8" in content
1166
1208
@@ -1175,7 +1217,7 b' def test_save_with_no_args():'
1175 with TemporaryDirectory() as tmpdir:
1217 with TemporaryDirectory() as tmpdir:
1176 path = os.path.join(tmpdir, "testsave.py")
1218 path = os.path.join(tmpdir, "testsave.py")
1177 ip.run_line_magic("save", path)
1219 ip.run_line_magic("save", path)
1178 content = Path(path).read_text()
1220 content = Path(path).read_text(encoding="utf-8")
1179 expected_content = dedent(
1221 expected_content = dedent(
1180 """\
1222 """\
1181 # coding: utf-8
1223 # coding: utf-8
@@ -1377,8 +1419,8 b' if __name__ == "__main__":'
1377 def test_run_module_from_import_hook():
1419 def test_run_module_from_import_hook():
1378 "Test that a module can be loaded via an import hook"
1420 "Test that a module can be loaded via an import hook"
1379 with TemporaryDirectory() as tmpdir:
1421 with TemporaryDirectory() as tmpdir:
1380 fullpath = os.path.join(tmpdir, 'my_tmp.py')
1422 fullpath = os.path.join(tmpdir, "my_tmp.py")
1381 Path(fullpath).write_text(TEST_MODULE)
1423 Path(fullpath).write_text(TEST_MODULE, encoding="utf-8")
1382
1424
1383 import importlib.abc
1425 import importlib.abc
1384 import importlib.util
1426 import importlib.util
@@ -1394,7 +1436,7 b' def test_run_module_from_import_hook():'
1394
1436
1395 def get_data(self, path):
1437 def get_data(self, path):
1396 assert Path(path).samefile(fullpath)
1438 assert Path(path).samefile(fullpath)
1397 return Path(fullpath).read_text()
1439 return Path(fullpath).read_text(encoding="utf-8")
1398
1440
1399 sys.meta_path.insert(0, MyTempImporter())
1441 sys.meta_path.insert(0, MyTempImporter())
1400
1442
@@ -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") 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') 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") 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
@@ -64,7 +64,7 b' def doctest_run_builtins():'
64
64
65 In [3]: fname = tempfile.mkstemp('.py')[1]
65 In [3]: fname = tempfile.mkstemp('.py')[1]
66
66
67 In [3]: f = open(fname,'w')
67 In [3]: f = open(fname, 'w', encoding='utf-8')
68
68
69 In [4]: dummy= f.write('pass\n')
69 In [4]: dummy= f.write('pass\n')
70
70
@@ -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') 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') 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') 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') 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') 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") 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") 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") 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") 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') 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') 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')
182 fil = open(fnam, "a", encoding="utf-8")
183 else:
183 else:
184 fil = open(fnam, 'w')
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") 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") 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") 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") 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") 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) 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').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}")')
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')
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,8 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 self.file = open(file_or_name, mode)
55 encoding = None if "b" in mode else "utf-8"
56 self.file = open(file_or_name, mode, encoding=encoding)
56 self.channel = channel
57 self.channel = channel
57 self.ostream = getattr(sys, channel)
58 self.ostream = getattr(sys, channel)
58 setattr(sys, channel, self)
59 setattr(sys, channel, self)
@@ -131,7 +132,7 b" def temp_pyfile(src, ext='.py'):"
131 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.
132 """
133 """
133 fname = tempfile.mkstemp(ext)[1]
134 fname = tempfile.mkstemp(ext)[1]
134 with open(Path(fname), "w") as f:
135 with open(Path(fname), "w", encoding="utf-8") as f:
135 f.write(src)
136 f.write(src)
136 f.flush()
137 f.flush()
137 return fname
138 return fname
@@ -24,7 +24,8 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 self.file = open(path, mode, bufsize)
27 encoding = None if "b" in mode else "utf-8"
28 self.file = open(path, mode, bufsize, encoding=encoding)
28
29
29 def cleanup(self):
30 def cleanup(self):
30 self.file.close()
31 self.file.close()
@@ -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').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').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').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').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") 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) as a_f:
459 with open(a, "rb") as a_f:
460 with open(b) 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").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
@@ -39,7 +39,7 b' def function(arg, *args, kwarg=True, **kwargs):'
39 pass is True
39 pass is True
40 False == None
40 False == None
41
41
42 with io.open(ru'unicode'):
42 with io.open(ru'unicode', encoding='utf-8'):
43 raise ValueError("\n escape \r sequence")
43 raise ValueError("\n escape \r sequence")
44
44
45 print("wěird ünicoðe")
45 print("wěird ünicoðe")
@@ -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") 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("")
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))
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") 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))
@@ -6,4 +6,4 b' sphinx-rtd-theme'
6 docrepr
6 docrepr
7 matplotlib
7 matplotlib
8 stack_data
8 stack_data
9 pytest
9 pytest<7
@@ -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) 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').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') 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') 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")
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) 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') 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()
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") 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).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