Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

raise an error when user tries to open a standard stream #13768

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions IPython/core/display.py
Expand Up @@ -625,6 +625,7 @@ def _data_and_metadata(self):
def _repr_json_(self):
return self._data_and_metadata()


_css_t = """var link = document.createElement("link");
link.ref = "stylesheet";
link.type = "text/css";
Expand Down
11 changes: 11 additions & 0 deletions IPython/core/interactiveshell.py
Expand Up @@ -270,6 +270,16 @@ def __repr__(self):
return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
(name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))

@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 "
"as it is likely to crash IPython. If you know what you are doing, "
"you can use builtins' open."
)

return io_open(file, *args, **kwargs)

class InteractiveShell(SingletonConfigurable):
"""An enhanced, interactive shell for Python."""
Expand Down Expand Up @@ -1323,6 +1333,7 @@ def init_user_ns(self):

ns['exit'] = self.exiter
ns['quit'] = self.exiter
ns["open"] = _modified_open

# Sync what we've added so far to user_ns_hidden so these aren't seen
# by %who
Expand Down
12 changes: 12 additions & 0 deletions IPython/core/tests/test_interactiveshell.py
Expand Up @@ -103,6 +103,18 @@ 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):
res = ip.run_cell("open(0)")
self.assertIsInstance(res.error_in_exec, ValueError)

def test_open_standard_output_stream(self):
res = ip.run_cell("open(1)")
self.assertIsInstance(res.error_in_exec, ValueError)

def test_open_standard_error_stream(self):
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'])
Expand Down