有没有办法在python中结合readline/rlcompleter和InteractiveConsole?

2024-05-13 18:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试扩展pythonshell(遗憾的是,我不能使用IPython)。我希望能够同时完成关键字和解释一些自定义输入(这不是有效的python)。但是我不能让readline/rlcompleter和InteractiveConsole协同工作。要演示问题:

$ python -c "import code; code.InteractiveConsole().interact()"
Python 2.7.10 (default, Jun  1 2015, 18:05:38)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import readline
>>> import rlcompleter
>>> readline.parse_and_bind("tab: complete")
>>> import string
>>> stri

点击这里的标签什么也不做。在

^{pr2}$

现在点击“字符串”完成。在

有人能解释一下为什么会这样吗?如果有办法的话?在


Tags: importdefaultreadlineonipythoncode关键字协同工作
1条回答
网友
1楼 · 发布于 2024-05-13 18:27:16

好吧-在python源代码中进行一些挖掘,可以找到答案。问题是在InteractiveConsole中,名称空间被设置为__main__以外的内容。但是rlcompleter从builtins__main__完成。^上面的{}导入到当前名称空间中,当前名称空间不是__main__,rlcompleter也不会搜索它。在

所以,一个解决办法就是建立你自己的完成者。完成者并将locals()传递给ctor:

$ python -c "import code; code.InteractiveConsole().interact()"
Python 2.7.10 (default, Jun  1 2015, 18:05:38) [GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import readline
>>> from rlcompleter import Completer
>>> readline.parse_and_bind("tab: complete")
>>> readline.set_completer(Completer(locals()).complete)
>>> import string
>>> str
str(    string

相关问题 更多 >