How to get a python script to invoke "python -i" when called normally?
From within script.py
, set the PYTHONINSPECT
environment variable to any nonempty string. Python will recheck this environment variable at the end of the program and enter interactive mode.
import os# This can be placed at top or bottom of the script, unlike code.interactos.environ['PYTHONINSPECT'] = 'TRUE'
In addition to all the above answers, you can run the script as simply ./script.py
by making the file executable and setting the shebang line, e.g.
#!/usr/bin/python -ithis = "A really boring program"
If you want to use this with the env
command in order to get the system default python
, then you can try using a shebang like @donkopotamus suggested in the comments
#!/usr/bin/env PYTHONINSPECT=1 python
The success of this may depend on the version of env
installed on your platform however.
You could use an instance of code.InteractiveConsole
to get this to work:
from code import InteractiveConsolei = 20d = 30InteractiveConsole(locals=locals()).interact()
running this with python script.py
will launch an interactive interpreter as the final statement and make the local names defined visible via locals=locals()
.
>>> i20
Similarly, a convenience function named code.interact
can be used:
from code import interacti = 20d = 30interact(local=locals())
This creates the instance for you, with the only caveat that locals
is named local
instead.
In addition to this, as @Blender stated in the comments, you could also embed the IPython
REPL by using:
import IPythonIPython.embed()
which has the added benefit of not requiring the namespace that has been populated in your script to be passed with locals
.