This is an IPython feature. If IPython thinks your input looks like it was copy-pasted from another interactive session, it will strip out everything it thinks is an interactive prompt before executing the input.
This is supposed to make it easy to copy and paste code from other interactive Python sessions without having to manually take the prompts off, but it causes problems when you have actual code that looks like it's got interactive prompts in it.
Contrary to what one of the other answers claims, editing sys.ps2
doesn't affect this at all. The prompt regexes are hardcoded. For current IPython, you can see the logic in IPython.core.inputtransformer2.PromptStripper
, but Google Colab is currently on an old IPython version, 5.5.0, where you should look at IPython.core.inputtransformer.classic_prompt
:
@CoroutineInputTransformer.wrap
def classic_prompt():
"""Strip the >>>/... prompts of the Python interactive shell."""
# FIXME: non-capturing version (?:...) usable?
prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)')
initial_re = re.compile(r'^>>>( |$)')
# Any %magic/!system is IPython syntax, so we needn't look for >>> prompts
turnoff_re = re.compile(r'^[%!]')
return _strip_prompts(prompt_re, initial_re, turnoff_re)
Editing sys.ps2
only looked like it helped because _strip_prompts
stops looking for prompts if it doesn't find any in the first two lines, and the extra code to edit sys.ps2
meant _strip_prompts
didn't find any prompts in those lines.
Unfortunately, if you want to disable this, it's going to be much more awkward than editing sys.ps2
. I don't think there's a convenient config option. I think you'll have to retrieve the list of input cleanup transformers and remove the prompt strippers manually. On the IPython version Google Colab currently uses, that looks like this:
physical_line_transforms = get_ipython().input_transformer_manager.physical_line_transforms
physical_line_transforms[:] = [transformer for transformer in physical_line_transforms
if transformer.coro.__name__ != '_strip_prompts']
coro
and _strip_prompts
are undocumented implementation details, but I don't think there's a better way.
On a more modern IPython, the code looks like this:
from IPython.core.inputtransformer2 import PromptStripper
cleanup_transformers = get_ipython().input_transformers_cleanup
cleanup_transformers[:] = [transformer for transformer in cleanup_transformers
if not isinstance(transformer, PromptStripper)]
Unlike the other snippet, I think everything here is part of the documented IPython API.
s.split("\n")
s.splitlines()
ands.split("\n")
...??['', '', '.o.', '', '']
when applying.split("\n")
s
actually is what you expected (i,e,'\n...\n.o.\n...\n'
) by printing it out (by removing.splitlines()
).'\n\n.o.\n\n'