How To Get A Python Script To Invoke "python -i" When Called Normally?
Solution 1:
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.interact
os.environ['PYTHONINSPECT'] = 'TRUE'
Solution 2:
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.
Solution 3:
You could use an instance of code.InteractiveConsole
to get this to work:
from code import InteractiveConsole
i = 20
d = 30
InteractiveConsole(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()
.
>>>i
20
Similarly, a convenience function named code.interact
can be used:
from code import interact
i = 20
d = 30
interact(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 IPython
IPython.embed()
which has the added benefit of not requiring the namespace that has been populated in your script to be passed with locals
.
Solution 4:
I think you're looking for this?
import code
foo = 'bar'print foo
code.interact(local=locals())
Solution 5:
I would simply accompany the script with a shell script that invokes it.
exec python -i "$(dirname "$0")/script.py"
Post a Comment for "How To Get A Python Script To Invoke "python -i" When Called Normally?"