From 2b682be9a35138ed82ece3a174db8a0e517cab08 Mon Sep 17 00:00:00 2001 From: Osher De Paz Date: Sat, 1 Oct 2022 11:46:26 +0300 Subject: [PATCH] raise an error when user tries to open a standard stream Fixes #13718 --- IPython/core/interactiveshell.py | 9 +++++++++ IPython/core/tests/test_interactiveshell.py | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 06912640673..1317af96f7a 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -1239,6 +1239,15 @@ def prepare_user_module(self, user_module=None, user_ns=None): 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 10827b5fa0f..b5efe98b85b 100644 --- a/IPython/core/tests/test_interactiveshell.py +++ b/IPython/core/tests/test_interactiveshell.py @@ -103,6 +103,21 @@ def test_syntax_error(self): 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'])