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