3
votes

Is there a way to make IPython console automatically reformat copied code, e.g.,

In [131]: a = [1, 2, 3]

In [132]: a
Out[132]: [1, 2, 3]

with standart Python prompt, i.e.,

>>> a = [1, 2, 3]
>>> a
[1, 2, 3]

The motivation is that:

  1. The line numbers (and perhaps the extra newline as well) make no sense here.
  2. The standard format is readily usable with doctest.

Interestingly, the Qt console of IPython offers both "Copy" and "Copy (Raw Text)", and the default behavior of "Copy" results in the following:

a = [1, 2, 3]

a
Out[132]: [1, 2, 3]

Apparently, some sort of automatic reformatting is achievable. Is there a way to customize this functionality?

I'm aware of PromptManager which can be used to customize the displayed prompt (e.g., http://nb.nathanamy.org/2012/09/terminal-productivity/). However, the IPython prompt (with numbers) is useful in interactive sessions. I only want the copied version to be reformatted.

2
Before you enter the code, you can toggle %doctest_mode on, which gives you the >>> prompts until you turn it off again. I think that's the closest thing we've got at present. - Thomas K
Thanks for mentioning this! %doctest_mode is indeed useful if one knows the code will be copied beforehand. Strangely, it seems not working with qtconsole... - herrlich10
That doesn't entirely surprise me - in the Qt console, prompts are generated by the frontend, while %doctest_mode acts in the kernel. You could look into adding a 'Copy with Python prompts' menu option. - Thomas K

2 Answers

1
votes

You can set the iPython configuration and check ipython section of this article.

Here are the steps:

1.Create profile

$ ipython profile create

2.Modify the following line into ~/.config/ipython/profile_default/ipython_config.py

c.PromptManager.in_template = '>>> '

After that, iPython shall work like you expected.

0
votes

I don't know of any built-in way to do this, but maybe you could help yourself by defining your own %magic function.

Something like

Stick to the docs for how to define and register a custom magic and 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 this myself, let's see if it works.

EDIT Seems like it doesn't work immediately, you'll have to figure out how to access In and Out inside a custom magic. But I'll leave the answer for reference, maybe someone else can finish the sample.