Copy the code from IPython console, automatically reformatted with standard Python hint
Is there a way to make the IPython console automatically reformat the copied code, for example
In [131]: a = [1, 2, 3]
In [132]: a
Out[132]: [1, 2, 3]
with a standard Python query i.e.
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
The motivation is as follows:
- Line numbers (and possibly an extra newline) don't make sense here.
- The standard format can be easily used with doctest.
Interestingly, IPython's Qt console offers both "Copy" and "Copy (Raw Text)" and the default "Copy" behavior results in the following:
a = [1, 2, 3]
a
Out[132]: [1, 2, 3]
Apparently some kind of automatic reformatting is possible. Is there a way to customize this functionality?
I know PromptManager
which one can be used to customize the prompt displayed (e.g. http://nb.nathanamy.org/2012/09/terminal-productivity/ ). However, the IPython prompt (with numbers) is useful in interactive sessions. I want the copied version to be reformatted.
source to share
You can tweak your iPython config and check the ipython section of this article .
Here are the steps:
1.Create a profile
$ ipython profile create
2. Edit the following line in ~ / .config / ipython / profile_default / ipython_config.py
c.PromptManager.in_template = '>>> '
After that iPython will work as you expected.
source to share
I don't know of any built-in way to do this, but perhaps you could help yourself by specifying your own% magic function.
Something like
Stick to the docs for defining and registering custom magic, then try something like:
from IPython.core.magic import (register_line_magic, register_cell_magic,
register_line_cell_magic)
@register_line_magic
def export_prompt(start, end):
"Exporting input and output within given limits"
for i in range(start, end):
in_ = In.get(i)
out_ = Out.get(i)
print in_
print out_
# We delete this to avoid name conflicts for automagic to work
del export_prompt
I'll try it myself, see if it works.
EDIT
It looks like this won't work right away, you need to figure out how to access In
and Out
inside the custom magic. But I'll leave the answer for reference, maybe someone else can finish the sample.
source to share