Launch ipython shell from python script that uses command line option parsing
I've been looking around for quite some time to find a way to optimally do this but haven't been successful. My problem setting is as follows:
I want to be able to launch an ipython shell for debugging purposes from within a python script that uses command line option parsing (optparse
), in a non-programmatic fashion.
To illustrate the issue, I have some example code bellow:
import sys
from optparse import OptionParser
class toolRunner(object):
def __init__(self):
self._parseOptions()
def _parseOptions(self):
usage = "Usage: %prog [--help] [options] input.cmp.h5"
parser = OptionParser(usage=usage)
parser.add_option('-r', type='string', dest='ins', default='1,2,3,4')
self.opts, args = parser.parse_args()
def main(self):
print testSum(self.opts.ins)
def testSum(dstr):
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
return sum(map(int,dstr.strip().split(',')))
if __name__ == '__main__':
sys.exit(toolRunner().main())
If I now call my test script test.py
as follows:
python test.py -r 1,2,3,4
I get the following error:
WARNING:
Error in Arguments: "Ambiguous option '-r'; matches ['readline', 'readline_merge_completions', 'readline_omit__names', 'rcfile']"
I guess ipython is trying to interpret the commandline option -r
as being destined for it. If I instead call the testSum(dstr)
function programmatically, then no such error is generated and I get an ipython shell to pop up. That is, if I substitute the following code in the above example:
if __name__ == '__main__':
# sys.exit(toolRunner().main())
testSum('1,2,3,4')
And run my script as:
python test.py -r 1,2,3,4
all runs well.
I have already 开发者_开发问答looked into alternatives i.e. using ipdb (Is it possible to go into ipython from code?), but would prefer doing it the way I am suggesting here due to the richness of features I get from the ipython shell as well as because it would be nice to know why my way doesn't work.
[Reposting as an answer since it worked]
Try specifying argv, like so: IPShellEmbed(argv=[])()
. That should stop IPython from looking at the arguments you gave to your script.
精彩评论