【问题标题】:Launch ipython shell from python script that uses command line option parsing从使用命令行选项解析的 python 脚本启动 ipython shell
【发布时间】:2011-05-25 01:09:47
【问题描述】:

我已经四处寻找了很长一段时间以找到一种最佳方式来做到这一点,但没有成功。我的问题设置如下:

我希望能够以非编程方式从使用命令行选项解析 (optparse) 的 python 脚本中启动 ipython shell 以进行调试

为了说明这个问题,我有一些示例代码如下:

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())

如果我现在调用我的测试脚本test.py 如下:

python test.py -r 1,2,3,4

我收到以下错误:

WARNING:
Error in Arguments: "Ambiguous option '-r';  matches ['readline', 'readline_merge_completions', 'readline_omit__names', 'rcfile']"

我猜 ipython 正试图将命令行选项 -r 解释为注定要使用它。如果我改为以编程方式调用 testSum(dstr) 函数,则不会生成此类错误,并且会弹出一个 ipython shell。也就是说,如果我在上面的示例中替换以下代码:

if __name__ == '__main__':
    # sys.exit(toolRunner().main())
    testSum('1,2,3,4')

并将我的脚本运行为:

python test.py -r 1,2,3,4

一切运行良好。

我已经研究过替代方案,即使用 ipdb (Is it possible to go into ipython from code?),但由于我从 ipython shell 获得的丰富功能以及它会很好知道为什么我的方法行不通。

【问题讨论】:

  • 未对此进行测试,但是:尝试指定 argv,如下所示:IPShellEmbed(argv=[])()。这应该会阻止 IPython 查看您提供给脚本的参数。
  • 很好,成功了!可能想将其发布为答案。
  • 优秀。我已经再次发布它作为答案。

标签: python debugging ipython


【解决方案1】:

[由于有效,因此作为答案重新发布]

尝试指定 argv,如下所示:IPShellEmbed(argv=[])()。这应该会阻止 IPython 查看您提供给脚本的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2021-09-26
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多