From 6a90b3afa67416a79d036a11880da4d33aad8e30 2022-10-29 11:18:09 From: Osher De Paz Date: 2022-10-29 11:18:09 Subject: [PATCH] raise an error when user tries to open a standard stream Fixes #13718 --- diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 6d04846..e9cc89a 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -1255,6 +1255,15 @@ class InteractiveShell(SingletonConfigurable): if user_ns is None: user_ns = user_module.__dict__ + @functools.wraps(io_open) + def modified_open(file, *args, **kwargs): + if file in {0, 1, 2}: + raise ValueError(f"IPython won't let you open fd={file} by default") + + return io_open(file, *args, **kwargs) + + user_ns["open"] = modified_open + return user_module, user_ns def init_sys_modules(self): diff --git a/IPython/core/tests/test_interactiveshell.py b/IPython/core/tests/test_interactiveshell.py index 10827b5..b5efe98 100644 --- a/IPython/core/tests/test_interactiveshell.py +++ b/IPython/core/tests/test_interactiveshell.py @@ -103,6 +103,21 @@ class InteractiveShellTestCase(unittest.TestCase): res = ip.run_cell("raise = 3") self.assertIsInstance(res.error_before_exec, SyntaxError) + def test_open_standard_input_stream(self): + ip.init_create_namespaces() + res = ip.run_cell("open(0)") + self.assertIsInstance(res.error_in_exec, ValueError) + + def test_open_standard_output_stream(self): + ip.init_create_namespaces() + res = ip.run_cell("open(1)") + self.assertIsInstance(res.error_in_exec, ValueError) + + def test_open_standard_error_stream(self): + ip.init_create_namespaces() + res = ip.run_cell("open(2)") + self.assertIsInstance(res.error_in_exec, ValueError) + def test_In_variable(self): "Verify that In variable grows with user input (GH-284)" oldlen = len(ip.user_ns['In'])