11

When calling IPython.embed() is it possible to give it a command or magic function to run after embedding happens.

I would like to run something like this

import IPython
IPython.embed(command='%pylab qt4')

My current workaround is to copy the command string to the clipboard, spawn a background thread which sends keystrokes %paste followed by enter to the current window. This works ok on linux, but it is very hacky and I can't get it working as well on Windows. It seems like it should be possible to specify this, but I've never grasped how the IPython configs are working or what arguments to embed are used for.

Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51
Erotemic
  • 4,806
  • 4
  • 39
  • 80

2 Answers2

6

The IPython.config package has been deprecated since IPython 4.0. You should import from traitlets.config instead.

import IPython
from pkg_resources import parse_version # installed with setuptools

if parse_version(IPython.release.version) >= parse_version('4.0.0'):
    from traitlets.config import Config
else:
    import IPython.config
    from IPython.config import Config

c = Config()
c.InteractiveShellApp.exec_lines = [
    '%pylab qt4'
    "print('System Ready!')",
]
IPython.start_ipython(config=c)
user503582
  • 309
  • 3
  • 4
3

The document stated that IPython.start_ipython reads the configuration file, while IPython.embed does not. With that in mind, let's use the former:

import IPython

c = IPython.Config()
c.InteractiveShellApp.exec_lines = [
    '%pylab qt4',
    "print 'System Ready!'",
]

IPython.start_ipython(config=c)

Update

I am not sure what you meant by to keep the current namespace. If you meant local/global variables:

IPython.start_ipython(config=c, user_ns=locals())   # Pass in local variables
IPython.start_ipython(config=c, user_ns=globals())  # Pass in global variables
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • 1
    This works, but is it possible to keep the current namespace as well? It looks like embed does that while start_ipython does not. – Erotemic Jan 13 '15 at 19:36