5

Say I have the following file t.py:

from IPython import get_ipython

if __name__ == '__main__':
    ip = get_ipython()
    if ip is not None:
        print('Found IPython')

Here's what happens if I run it, with both Python and IPython:

% python t.py
% ipython t.py 
Found IPython

Note that, only when running it with ipython, is get_ipython() not None.

Is there a way to start an IPython kernel from within the script, so that even if I run it as python t.py, then get_ipython() will not be None?

2
  • Did you try calling IPython.start_kernel()? Commented Jun 21, 2021 at 18:27
  • yes, and got ``` warn("The IPython.kernel package has been deprecated since IPython 4.0." NOTE: When using the ipython kernel entry point, Ctrl-C will not work. To exit, you will have to explicitly quit this process, by either sending "quit" from a client, or using Ctrl-\ in UNIX-like environments. To read more about this, see github.com/ipython/ipython/issues/2049 To connect another client to this kernel, use: --existing kernel-15293.json ``` Commented Jun 21, 2021 at 18:30

1 Answer 1

4
+100

IPython starts new interactive shell, i.e. your code will be suspended until IPython shell is terminated.

You can have a launcher in a separate file, launcher.py:

import IPython

if __name__ == '__main__':
    IPython.start_ipython(['t.py'])
% python launcher.py
Found IPython

For other options of embedding IPython see the docs https://ipython.readthedocs.io/en/stable/interactive/reference.html#embedding-ipython

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! I have a question though - suppose t.py ends with sys.exit(1). Then, running python t.py will work without exceptions, and the return code will be 1, while python launcher.py will through a SystemExit error and show a traceback. Could launcher.py preserve the exit code of t.py?
@ignoring_gravity You can capture SystemExit exception which has code value, then sys.exit with that value.
Do you mean to put that in launcher.py? I've tried, and it's not working for me
Yes, you can capture SystemExit and return its code in launcher.py, but t.py will still print stack trace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.