##// END OF EJS Templates
Format code
gousaiyang -
Show More
@@ -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, encoding='utf-8')
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', encoding='utf-8')
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,7 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 encoding = None if 'b' in self._read_flags else 'utf-8'
352 encoding = None if "b" in self._read_flags else "utf-8"
353 353 with open(self.filename, self._read_flags, encoding=encoding) as f:
354 354 self.data = f.read()
355 355 elif self.url is not None:
@@ -370,8 +370,11 b' class DisplayObject(object):'
370 370 if 'gzip' in response.headers['content-encoding']:
371 371 import gzip
372 372 from io import BytesIO
373
373 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 378 encoding = None
376 379 data = fp.read()
377 380
@@ -2626,7 +2626,7 b' class InteractiveShell(SingletonConfigurable):'
2626 2626
2627 2627 # Make sure we can open the file
2628 2628 try:
2629 with fname.open('rb'):
2629 with fname.open("rb"):
2630 2630 pass
2631 2631 except:
2632 2632 warn('Could not open file <%s> for safe execution.' % fname)
@@ -2684,7 +2684,7 b' class InteractiveShell(SingletonConfigurable):'
2684 2684
2685 2685 # Make sure we can open the file
2686 2686 try:
2687 with fname.open('rb'):
2687 with fname.open("rb"):
2688 2688 pass
2689 2689 except:
2690 2690 warn('Could not open file <%s> for safe execution.' % fname)
@@ -2706,7 +2706,7 b' class InteractiveShell(SingletonConfigurable):'
2706 2706 if cell.cell_type == 'code':
2707 2707 yield cell.source
2708 2708 else:
2709 yield fname.read_text(encoding='utf-8')
2709 yield fname.read_text(encoding="utf-8")
2710 2710
2711 2711 with prepended_to_syspath(dname):
2712 2712 try:
@@ -3458,7 +3458,7 b' class InteractiveShell(SingletonConfigurable):'
3458 3458 self.tempfiles.append(file_path)
3459 3459
3460 3460 if data:
3461 file_path.write_text(data, encoding='utf-8')
3461 file_path.write_text(data, encoding="utf-8")
3462 3462 return filename
3463 3463
3464 3464 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(encoding='utf-8')
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(encoding='utf-8')
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(encoding='utf-8')
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(encoding='utf-8')
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, encoding='utf-8')
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(encoding='utf-8')
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", encoding='utf-8') 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, encoding='utf-8'), 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, encoding='utf-8').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", encoding='utf-8') 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", encoding='utf-8') 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", encoding='utf-8').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", encoding='utf-8').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", encoding='utf-8').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", encoding='utf-8') 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", encoding='utf-8') 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', encoding='utf-8').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', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') 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", encoding='utf-8') 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)
@@ -861,12 +861,18 b' def test_file():'
861 861 """Basic %%writefile"""
862 862 ip = get_ipython()
863 863 with TemporaryDirectory() as td:
864 fname = os.path.join(td, 'file1')
865 ip.run_cell_magic("writefile", fname, u'\n'.join([
866 'line1',
867 'line2',
868 ]))
869 s = Path(fname).read_text(encoding='utf-8')
864 fname = os.path.join(td, "file1")
865 ip.run_cell_magic(
866 "writefile",
867 fname,
868 "\n".join(
869 [
870 "line1",
871 "line2",
872 ]
873 ),
874 )
875 s = Path(fname).read_text(encoding="utf-8")
870 876 assert "line1\n" in s
871 877 assert "line2" in s
872 878
@@ -876,12 +882,18 b' def test_file_single_quote():'
876 882 """Basic %%writefile with embedded single quotes"""
877 883 ip = get_ipython()
878 884 with TemporaryDirectory() as td:
879 fname = os.path.join(td, '\'file1\'')
880 ip.run_cell_magic("writefile", fname, u'\n'.join([
881 'line1',
882 'line2',
883 ]))
884 s = Path(fname).read_text(encoding='utf-8')
885 fname = os.path.join(td, "'file1'")
886 ip.run_cell_magic(
887 "writefile",
888 fname,
889 "\n".join(
890 [
891 "line1",
892 "line2",
893 ]
894 ),
895 )
896 s = Path(fname).read_text(encoding="utf-8")
885 897 assert "line1\n" in s
886 898 assert "line2" in s
887 899
@@ -892,11 +904,17 b' def test_file_double_quote():'
892 904 ip = get_ipython()
893 905 with TemporaryDirectory() as td:
894 906 fname = os.path.join(td, '"file1"')
895 ip.run_cell_magic("writefile", fname, u'\n'.join([
896 'line1',
897 'line2',
898 ]))
899 s = Path(fname).read_text(encoding='utf-8')
907 ip.run_cell_magic(
908 "writefile",
909 fname,
910 "\n".join(
911 [
912 "line1",
913 "line2",
914 ]
915 ),
916 )
917 s = Path(fname).read_text(encoding="utf-8")
900 918 assert "line1\n" in s
901 919 assert "line2" in s
902 920
@@ -905,13 +923,19 b' def test_file_var_expand():'
905 923 """%%writefile $filename"""
906 924 ip = get_ipython()
907 925 with TemporaryDirectory() as td:
908 fname = os.path.join(td, 'file1')
909 ip.user_ns['filename'] = fname
910 ip.run_cell_magic("writefile", '$filename', u'\n'.join([
911 'line1',
912 'line2',
913 ]))
914 s = Path(fname).read_text(encoding='utf-8')
926 fname = os.path.join(td, "file1")
927 ip.user_ns["filename"] = fname
928 ip.run_cell_magic(
929 "writefile",
930 "$filename",
931 "\n".join(
932 [
933 "line1",
934 "line2",
935 ]
936 ),
937 )
938 s = Path(fname).read_text(encoding="utf-8")
915 939 assert "line1\n" in s
916 940 assert "line2" in s
917 941
@@ -935,16 +959,28 b' def test_file_amend():'
935 959 """%%writefile -a amends files"""
936 960 ip = get_ipython()
937 961 with TemporaryDirectory() as td:
938 fname = os.path.join(td, 'file2')
939 ip.run_cell_magic("writefile", fname, u'\n'.join([
940 'line1',
941 'line2',
942 ]))
943 ip.run_cell_magic("writefile", "-a %s" % fname, u'\n'.join([
944 'line3',
945 'line4',
946 ]))
947 s = Path(fname).read_text(encoding='utf-8')
962 fname = os.path.join(td, "file2")
963 ip.run_cell_magic(
964 "writefile",
965 fname,
966 "\n".join(
967 [
968 "line1",
969 "line2",
970 ]
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 984 assert "line1\n" in s
949 985 assert "line3\n" in s
950 986
@@ -954,11 +990,17 b' def test_file_spaces():'
954 990 ip = get_ipython()
955 991 with TemporaryWorkingDirectory() as td:
956 992 fname = "file name"
957 ip.run_cell_magic("file", '"%s"'%fname, u'\n'.join([
958 'line1',
959 'line2',
960 ]))
961 s = Path(fname).read_text(encoding='utf-8')
993 ip.run_cell_magic(
994 "file",
995 '"%s"' % fname,
996 "\n".join(
997 [
998 "line1",
999 "line2",
1000 ]
1001 ),
1002 )
1003 s = Path(fname).read_text(encoding="utf-8")
962 1004 assert "line1\n" in s
963 1005 assert "line2" in s
964 1006
@@ -1154,11 +1196,11 b' def test_save():'
1154 1196 with TemporaryDirectory() as tmpdir:
1155 1197 file = os.path.join(tmpdir, "testsave.py")
1156 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 1200 assert content.count(cmds[0]) == 1
1159 1201 assert "coding: utf-8" in content
1160 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 1204 assert content.count(cmds[0]) == 2
1163 1205 assert "coding: utf-8" in content
1164 1206
@@ -1173,7 +1215,7 b' def test_save_with_no_args():'
1173 1215 with TemporaryDirectory() as tmpdir:
1174 1216 path = os.path.join(tmpdir, "testsave.py")
1175 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 1219 expected_content = dedent(
1178 1220 """\
1179 1221 # coding: utf-8
@@ -1335,8 +1377,8 b' if __name__ == "__main__":'
1335 1377 def test_run_module_from_import_hook():
1336 1378 "Test that a module can be loaded via an import hook"
1337 1379 with TemporaryDirectory() as tmpdir:
1338 fullpath = os.path.join(tmpdir, 'my_tmp.py')
1339 Path(fullpath).write_text(TEST_MODULE, encoding='utf-8')
1380 fullpath = os.path.join(tmpdir, "my_tmp.py")
1381 Path(fullpath).write_text(TEST_MODULE, encoding="utf-8")
1340 1382
1341 1383 import importlib.abc
1342 1384 import importlib.util
@@ -1352,7 +1394,7 b' def test_run_module_from_import_hook():'
1352 1394
1353 1395 def get_data(self, path):
1354 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 1399 sys.meta_path.insert(0, MyTempImporter())
1358 1400
@@ -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", encoding='utf-8') 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', encoding='utf-8') 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", encoding='utf-8') 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
@@ -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', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') 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", encoding='utf-8') 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", encoding='utf-8') 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", encoding='utf-8') 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", encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8')
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', encoding='utf-8')
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", encoding='utf-8') 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", encoding='utf-8') 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", encoding='utf-8') 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", encoding='utf-8') 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", encoding='utf-8') 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, encoding='utf-8') 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', encoding='utf-8').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}")', encoding='utf-8')
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', encoding='utf-8')
23 devnull = open(os.devnull, "w", encoding="utf-8")
24 24 atexit.register(devnull.close)
25 25
26 26
@@ -52,7 +52,7 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 encoding = None if 'b' in mode else 'utf-8'
55 encoding = None if "b" in mode else "utf-8"
56 56 self.file = open(file_or_name, mode, encoding=encoding)
57 57 self.channel = channel
58 58 self.ostream = getattr(sys, channel)
@@ -132,7 +132,7 b" def temp_pyfile(src, ext='.py'):"
132 132 It is the caller's responsibility to close the open file and unlink it.
133 133 """
134 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 136 f.write(src)
137 137 f.flush()
138 138 return fname
@@ -24,7 +24,7 b' class NamedFileInTemporaryDirectory(object):'
24 24 """
25 25 self._tmpdir = TemporaryDirectory(**kwds)
26 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 28 self.file = open(path, mode, bufsize, encoding=encoding)
29 29
30 30 def cleanup(self):
@@ -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', encoding='utf-8').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', encoding='utf-8').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', encoding='utf-8').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', encoding='utf-8').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", encoding='utf-8') 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, 'rb') as a_f:
460 with open(b, 'rb') 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", encoding='utf-8').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
@@ -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", encoding='utf-8') 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("", encoding='utf-8')
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), encoding='utf-8')
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", encoding='utf-8') 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))
@@ -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, encoding='utf-8') 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', 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 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', encoding='utf-8') 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', encoding='utf-8') 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", encoding='utf-8')
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, encoding='utf-8') 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', encoding='utf-8') 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(encoding='utf-8')
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", encoding='utf-8') 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, 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